在'onmouseover'中修改HTML's CSS属性事件

JavaScript Changing HTML's CSS Attributes in the 'onmouseover' event

本文关键字:CSS 属性 事件 onmouseover 修改 HTML      更新时间:2023-09-26

我需要改变我的HTML <li>元素的边框颜色,当用户把光标放在项目上,还需要改变光标图标,当鼠标在项目上。我试过了,但是显示"语法错误"

<li class="post-item-parent-div" onmouseover="onItemHover(this)" >
    <!-- More HTML Code -->
</li>
Javascript

function onItemHover(x) {
    x.border-top = "12px solid #0084FD";
    x.border-left = "12px solid #0084FD";
    x.cursor = "pointer";
}

我对JavaScript很陌生,所以请帮助:)

你需要像下面这样改变css属性名,因为带有-的样式名不能直接在javascript中使用。

参见 javascript

中CSS属性的引用名称

function onItemHover(x) {
  x.style.borderTop = "12px solid #0084FD";
  x.style.borderLeft = "12px solid #0084FD";
  x.style.cursor = "pointer";
}
<ul>
  <li class="post-item-parent-div" onmouseover="onItemHover(this)">
    some code
  </li>
</ul>


但也要注意,当你移动到同一父元素li中的另一个元素时,mouseover事件将被触发,所以你可能会考虑使用mouseenter事件

function onItemHover(x) {
  snippet.log('on over')
}
function onEnter(x) {
  snippet.log('on enter');
  
  x.style.borderTop = "12px solid #0084FD";
  x.style.borderLeft = "12px solid #0084FD";
  x.style.cursor = "pointer";
}
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<ul>
  <li class="post-item-parent-div" onmouseover="onItemHover(this)" onmouseenter="onEnter(this)">
    some code <span>in span</span>  <a href="#">in link</a>
  </li>
</ul>

为什么不使用:hover选择器?

li.post-item-parent-div:hover
{
    border-top: 12px solid #0084FD;
    border-left: 12px solid #0084FD;
    cursor: pointer;
}

JSFiddle示例:https://jsfiddle.net/zt66jf39/

这样做:

function onItemHover(x) {
   x.setAttribute("style", "border-top: 12px solid #0084FD; border-left: 12px solid #0084FD;cursor:pointer;");
}

添加以下代码

    var item = document.getElementById("button");
item.addEventListener("mouseover", func, false);
item.addEventListener("mouseout", func1, false);
function func()
{  // not needed since item is already global, 
   // I am assuming this is here just because it's sample code?
   // var item = document.getElementById("button"); 
   item.setAttribute("style", "background-color:blue;")
}
function func1()
{  
   item.setAttribute("style", "background-color:green;")
}