Javascript在' onmouseover'中更改HTML的CSS属性事件

时间:2015-09-16 03:58:56

标签: javascript html javascript-events

当用户将光标放在项目上时,我需要更改HTML <li>元素的边框颜色,当鼠标悬停在项目上时,我也需要更改光标图标。我尝试了这个,但它说&#34;语法错误&#34;

HTML

<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很新,所以请帮帮忙:)

4 个答案:

答案 0 :(得分:2)

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

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

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

答案 1 :(得分:2)

您需要更改下面的css属性名称,因为-的样式名称无法直接在javascript中使用。

有关javacsript

中css属性的引用名称,请参阅CSS Properties Reference

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>

答案 2 :(得分:1)

这样做:

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

答案 3 :(得分:1)

添加此代码

    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;")
}