Javascript onmouseover and onmouseout

别等时光非礼了梦想. 提交于 2019-11-30 16:37:58

As Paul S. suggests, you need to pass this to the function so that it knows which element it has to work on.

<div onmouseout="normal(this);" onmouseover="hover(this);" >
    <p>LOLOL</p>
</div>
<div onmouseout="normal(this);" onmouseover="hover(this);" >
    <p>LOLOL</p>
</div>
<div onmouseout="normal(this);" onmouseover="hover(this);" >
    <p>LOLOL</p>
</div>
<div onmouseout="normal(this);" onmouseover="hover(this);" >
    <p>LOLOL</p>
</div>

And then select the child element <p> for the passed <div>. Here I select the first child p, i.e. the first element in the array of children of this element with tag p, that's why you see [0]. So if in each div you had two paragraph, then you could use e.g. getElementsByTagName("p")[1] to select the second <p>.

function normal(mydiv) {
    mydiv.getElementsByTagName("p")[0].style.opacity="0.5";
}
function hover(mydiv) {
    mydiv.getElementsByTagName("p")[0].style.opacity="1";
}

See the working example here: http://jsfiddle.net/mastazi/2REe5/

Your html should be something like this:

<div onmouseout="normal(1);" onmouseover="hover(1);">
  <p id="something-1">LOLOL</p>
</div>
<div onmouseout="normal(2);" onmouseover="hover(2);">
  <p id="something-2">LOLOL</p>
</div>
<div onmouseout="normal(3);" onmouseover="hover(3);">
  <p id="something-3">LOLOL</p>
</div>
<div onmouseout="normal(4);" onmouseover="hover(4);">
  <p id="something-4">LOLOL</p>
</div>

As you can see, we have different ids for your elements, and we pass the ids through the function that we trigger with onlouseover and onmouseout.

For your javascript, your code could be something like this:

function normal(id) {
  var something = document.getElementById('something-'+id);
  something.style.opacity = "0.5";
}

function hover(id) {
  var something = document.getElementById('something-'+id);
  something.style.opacity = "1";
}

For normal() and hover() we receive an id and change the style for the current element that have this id.

Please, check this JSFiddle that I've built for you.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!