如何使用 JavaScript 或 JQuery 模拟悬停事件



我想使用 JS 或任何其他库模拟鼠标悬停在元素上。

我为示例创建了这个并添加了一些 CSS 以查看何时悬停<p>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Hover test</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <style>
        .red:hover {
            color:red;
        }
        .red:focus {
            color:green;
        }
    </style>
</head>
<body>
    <p class="red">test</p>
</body>
</html>

所以当你把手指放在文本上时,它会变红。

我尝试了一些 JQuery 函数,例如 mouseover()hover()但这些都是事件。

我只是想使用一些JS指令使文本变红。

试试这段代码:

function simulateMouseover() {
  var event = new MouseEvent('mouseover', {
    'view': window,
    'bubbles': true,
    'cancelable': true
  });
  var myTarget = document.querySelector('.red'); 
  var canceled = !myTarget.dispatchEvent(event);
  if (canceled) {
    // A handler called preventDefault.
    alert("canceled");
  } else {
    // None of the handlers called preventDefault.
    alert("not canceled");
  }
}
function mouseOverBehaviour() {
    myElement = document.querySelector('.red'); 
     // attach mouseover event listener to element
    myElement.addEventListener("mouseover", function(event) {
        // change the color of the font
        event.target.style.color = "red";
    });  
    // call the simulation
    setTimeout(simulateMouseover,3000);
}
mouseOverBehaviour();
$("p").hover(function(){
  $(this).css("background-color", "yellow");
  }, function(){
  $(this).css("background-color", "pink");
});

jQuery也可以做到这一点。玩得愉快。如果您有任何问题,请告诉我

https://www.w3schools.com/jquery/event_hover.asp

最新更新