gpt4 book ai didi

javascript - 如何在不移动鼠标的情况下加载页面时触发鼠标事件?

转载 作者:行者123 更新时间:2023-11-28 00:02:43 28 4
gpt4 key购买 nike

我有一个指向我主页的链接,当鼠标经过它时它会改变颜色。但是,当用户单击时,页面会刷新并且链接会变回原来的颜色。我希望链接再次更改为新颜色只是因为鼠标在那里,但是鼠标停止时没有触发鼠标事件。在 JSFiddle , 但是,它有效(将鼠标放在文本上并使用 F5 刷新所有页面),所以我想一定有办法。我不想使用 css :hover 因为颜色经常改变,而且我发现在 javascript 中改变 css 值是一种噩梦。或者不是吗?另外,请不要使用 JQuery。

function colorize() {
this.style.color = '#C83';
}
function load() {
var p1 = document.getElementById('p1');
p1.addEventListener('mouseover',colorize);
}
p {
font-size: 2em;
background-color: #385;
}
<body onload='load()'>
<p id='p1'>Some big text</p>
</body>

最佳答案

老实说,你的这个场景

When the user clicks, however, the page refreshes and the link turns back to the old color.

似乎更像是强制刷新页面的问题。为什么要强制刷新?

基于此thread ,

You can't. It's not a trusted event.

Events that are generated by the user agent, either as a result of user interaction, or as a direct result of changes to the DOM, are trusted by the user agent with privileges that are not afforded to events generated by script through the DocumentEvent.createEvent("Event") method, modified using the Event.initEvent() method, or dispatched via the EventTarget.dispatchEvent() method. The isTrusted attribute of trusted events has a value of true, while untrusted events have a isTrusted attribute value of false.

Most untrusted events should not trigger default actions, with the exception of click or DOMActivate events.

You have to add a class and add/remove that on the mouseover/mouseout events manually

只是没有标准/值得一提的本地方式来做到这一点。

刷新时您必须以某种方式保留状态。传递查询字符串 ?isMouseOver=true 并在刷新后解析它就足够了。只需在验证查询字符串后执行相同的鼠标悬停函数,无需以编程方式触发鼠标悬停事件。

或者你可以使用 jQuery,which has trigger-able mouse events.


但老实说,我会避免强制刷新解决方案并想出其他办法

关于javascript - 如何在不移动鼠标的情况下加载页面时触发鼠标事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55913099/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com