【问题标题】:Why is mouseover function not working为什么鼠标悬停功能不起作用
【发布时间】:2016-11-05 22:43:55
【问题描述】:

我有最简单的代码,但我之前从未尝试过使用 onmouseover,所以不知道为什么它不起作用:

<div class="play" id="buttonPlay">
    <img src="Buttons/Play/playRest.png" onmouseover="this.src='Buttons/Play/playClick.png'" width="100%"> 
</div>

有什么想法吗?什么是调试它的好方法?

【问题讨论】:

  • 我复制了替换为alert() 的代码并显示了警报,因此它应该正在运行。
  • Open the browser's JS console 看看错误信息是什么。
  • 定义“不工作”。图像是否被损坏的图像替换?控制台中是否显示错误消息?什么都没有发生吗?
  • 该代码真的重现了问题吗?还是仅在(例如)添加其他 HTML 元素和 CSS 时发生?
  • 不,它根本不起作用。控制台上没有错误。我也尝试用 alert() 替换,但仍然没有。

标签: javascript html image mouseover


【解决方案1】:

尝试在脚本元素中声明您的函数并引用该函数,而不是全部内联。至少这样您就可以在浏览器的开发者控制台中设置断点并查看发生了什么。

<div class="play" id="buttonPlay">
    <img src="Buttons/Play/playRest.png" onmouseover="myFunction(this)" width="100%"> 
</div>
<script>
    function myFunction(element) {
        element.src='Buttons/Play/playClick.png';
    }
</script>

【讨论】:

  • 重新编辑:现在你没有破坏它,但你似乎没有解决问题。您只是建议进行一行调试。 (通过将debugger; 附加到onmouseover 属性值来设置断点会更容易)
  • @Quentin 你说得对,我编辑了它,但这不是一个解决方案,它只是一种方便调试的方法。
【解决方案2】:

尝试使用 setAttribute 代替,当我这样做时,它可以工作。

<div class="play" id="buttonPlay">
    <img src="Buttons/Play/playRest.png" onmouseover="this.setAttribute('src', 'Buttons/Play/playClick.png');" width="100%"> 
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-08
    • 2011-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    相关资源
    最近更新 更多