【问题标题】:Can I change button position depending on the cursor position?我可以根据光标位置更改按钮位置吗?
【发布时间】:2018-04-12 11:43:50
【问题描述】:

我还是 javascript 新手,所以很遗憾我还不知道其中的正确命令。 所以我有这段代码,带有一个可以滚动回顶部的按钮,我想知道是否有办法根据光标的位置更改该按钮的位置?例如,如果光标位于站点的右侧,则按钮将显示在右侧。 代码很长我不指望你自己写,如果你能告诉我需要使用哪些命令就足够了,那我自己试试吧

感谢任何帮助!

<button onclick="topFunction()" id="topB" title="Go to top">Top</button>



#topB {
display: none; 
position: fixed; 
bottom: 20px; 
right: 30px; 
z-index: 99; 
border: none; 
outline: none; 
background-color: gray; 
color: white; 
cursor: pointer; 
padding: 15px;
border-radius: 10px;
font-size: 18px; 
}

#topB:hover {
color:black;
background-color: red; 
}


window.onscroll = function() {scrollFunction()};

function scrollFunction() {
// After scrolling down "number"px, the button appears
if (document.body.scrollTop >= 10 || document.documentElement.scrollTop >= 
10) {
    document.getElementById("topB").style.display = "block";
} else {
    document.getElementById("topB").style.display = "none";
}
}
function topFunction() {
// Scrolls to the top on click
document.body.scrollTop = 0; 
document.documentElement.scrollTop = 0; 
}

【问题讨论】:

标签: html css button position cursor


【解决方案1】:

使用 mousehover 事件并获取指针的 x 和 y 坐标。现在使用 window.innerWidth 获取屏幕的总宽度现在使用指针的 x 位置确定我是哪个半指针并相应地更改 css。如果您需要更多帮助,我可以帮助您

【讨论】:

  • 如果您不介意,可以帮帮我吗?所以我制作了这段代码(不是在 6 小时内,现在只有空闲时间)function buttonchangeP(event){ var x = event.clientX; var y = event.clientY; if(x&lt;=950){ document.getElementById("topBR").style.right="30px"; } else{ document.getElementById("topBR").style.left="30px" ; } } 它确实改变了按钮的位置,但只有一次我应该添加什么以便它不间断地执行?
  • 没关系,解决了,只需要把右边换成左边,然后在else部分将px设置为更高的数字,(本例中为1800px)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-03-14
  • 2015-03-03
  • 2014-05-25
  • 1970-01-01
  • 1970-01-01
  • 2015-05-29
  • 1970-01-01
相关资源
最近更新 更多