我正在写两个文件-一个是html,一个是JavaScript。所以我叫一个对象
document.getElementById("nameObj").onmouseover = changeMe;
然后在JavaScript文件中
changeMe = function()
{
//and here i write the function
}
但是现在我正在尝试优化代码并调用其中包含对象的函数。我创建了部分(其中4个部分),并且尝试使用onmouseover
和更改颜色onmouseout
。这是html的代码:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"> </script>
<title> test 2</title>
</head>
<body>
<header> </header>
<div id="wrapper">
<main>
<section class="mysection" id="section1"> </section>
<section class="mysection" id="section2"> </section>
<section class="mysection" id="section3"> </section>
<section class="mysection" id="section4"> </section>
</main>
<div class="clear"> </div>
</div>
<footer> </footer>
<script>
(function(){
var sec = document.getElementsByClassName("mysection");
for(var i=0; i<3; i++)
{
sec[i].onmouseover=changeMe(sec[i], i);
sec[i].onmouseout=changeBack(sec[i]);
}
})();
</script>
</body>
</html>
这是JS:
function changeMe(t_section, count)
{
if(count==0)
{
t_section.style.background="yellow";
}
if(count==1)
{
t_section.style.background="blue";
}
if(count==2)
{
t_section.style.background="green";
}
if(count==3)
{
t_section.style.background="red";
}
};
function changeBack(t_section)
{
t_section.style.background="gray";
};
但这不起作用。我做错什么了?
将您的脚本标签更改为以下代码:
(function(){
var sec = document.getElementsByClassName("mysection");
for(var i = 0; i < 4; i++)
{
sec[i].addEventListener('mouseover', function() {
var index = i;
return function() {
changeMe(sec[index], index);
};
}());
sec[i].addEventListener('mouseout', function() {
var index = i;
return function() {
changeBack(sec[index]);
};
}());
}
})();
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句