簡體   English   中英

如何使用JavaScript或JQuery模擬懸停事件?

[英]How to simulate an hover event, using JavaScript or 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM