按钮在手机屏幕上点击后保持:悬停效果

问题描述 投票:0回答:3

我有一个滚动到顶部按钮,当它在移动屏幕上单击时,它会保留我为其悬停效果设置的颜色,并且不会返回到原始颜色。

#back-to-top {
  background: none;
  background-repeat: no-repeat;
  border: none;
  cursor: pointer;
  overflow: hidden;
  outline: none;
  position: fixed;
  bottom: 30px;
  right: 20px;
  color: rgb(255, 51, 0);
  z-index: 99;
  font-size: 2.5rem;
}

#back-to-top:hover {
  color: rgb(255, 0, 140);
}

这是按钮的初始颜色:

在移动屏幕上单击它后,它会保持新颜色,直到我单击屏幕上的某个位置:

这只发生在触摸屏上,而不是桌面上,因为悬停效果在某种程度上被视为触摸屏的焦点。

如何避免这种情况并在点击后保持原来的颜色?

javascript html css
3个回答
3
投票

仅当设备具有真正的悬停功能时才尝试更改悬停时的颜色:

#back-to-top {
  background: none;
  background-repeat: no-repeat;
  border: none;
  cursor: pointer;
  overflow: hidden;
  outline: none;
  position: fixed;
  bottom: 30px;
  right: 20px;
  color: rgb(255, 51, 0);
  z-index: 99;
  font-size: 2.5rem;
}

@media (hover: hover) {
  #back-to-top:hover {
    color: rgb(255, 0, 140);
  }
}
<button id="back-to-top">Top</button>


2
投票

由于 CSS Media Queries Level 4 的这一部分自 2018 年以来已得到广泛实施,因此您可以使用它

@media (hover: hover) {
button:hover {
    background-color: blue;
   } }

0
投票

如果有人仍然遇到移动设备上“粘性”悬停元素的问题,我找到了一个很好的解决方案!

使用 javascript,我们可以在页面中添加一个触摸监听器来检测何时触摸屏幕,然后模拟“鼠标松开”事件,这将消除屏幕上的粘性点击!

document.addEventListener('DOMContentLoaded', function() {
    // Function to determine if the device is touch-enabled
    function isTouchDevice() {
        return ('ontouchstart' in window) || (navigator.maxTouchPoints > 0) || (navigator.msMaxTouchPoints > 0);
    }

    if (isTouchDevice()) {
        // Listen for touchend events on the entire document
        document.addEventListener('touchend', function(e) {
            
            // Simulate a mouse unclick by dispatching a 'mouseup' event
            let mouseUpEvent = new MouseEvent('mouseup', {
                bubbles: true,
                cancelable: true,
                view: window
            });
            
            // Dispatch the mouseup event on the target of the touch event
            e.target.dispatchEvent(mouseUpEvent);
            
            // Optionally, blur the active element to clear focus
            if (document.activeElement && document.activeElement !== document.body) {
                document.activeElement.blur();
            }
        });
    }
});
© www.soinside.com 2019 - 2024. All rights reserved.