您可以在此处查看代码:http : //jsfiddle.net/KfwyL/我有一个div,并且在div内有一个h1。我设置了h1,以便在悬停时变为绿色。我想这样做,以便当鼠标悬停在h1上时,div会获得一个框阴影。我的代码无法正常工作。
HTML:
<!DOCTYPE html>
<head>
<link rel="stylesheet" type="text/css" href="../stylesheets/1.css">
<title> Max Pleaner's First Website
</title>
</head>
<body>
<div class="welcomebox">
<h1 class="welcometext">Welcome to my site.
</h1>
</div>
</body>
<<script src="../Scripts/1.js"> </script>
</html>
CSS:
body {
background-image:url('../images/sharks.jpg');
}
.welcomebox {background-color:#1C0245;
-webkit-border-radius: 18px;
-moz-border-radius: 18px;
border-radius: 18px;
width: 390px;
height: 78px;
margin-left:100px;
margin-top:28px;
border-style:solid;
border-width:medium;
}
h1 {
display:inline-block;
margin-left: 12px;
height: 40px;
width: 357px;
background-color: #670715;
padding: 4px;
position: relative;
bottom: 5px;
-webkit-border-radius: 14px;
-moz-border-radius: 14px;
border-radius: 14px;
}
h1:hover {background-color: green;}
Javascript:
welcomeboxshadow = document.getElementsByClass("welcometext");
function doit()
{
var topbox = document.getElementsbyClass("welcomebox")
topbox.style.box-shadow = "-webkit-box-shadow: 0px 0px 30px rgba(114, 220, 215, 1);-moz-box-shadow: 0px 0px 30px rgba(114, 220, 215, 1);box-shadow: 0px 0px 30px rgba(114, 220, 215, 1);"
};
welcomeboxshadow.onmouseover.doit;
这是您不使用jQuery的代码的有效版本,因为我认为您想知道如何在纯JS中执行此操作...
welcomeboxshadow = document.getElementsByClassName("welcometext");
welcomeboxshadow[0].addEventListener('mouseover',
function() {
var topbox = document.getElementsByClassName("welcomebox");
topbox[0].setAttribute("class","welcomebox welcomeBoxMouseOver")
}, false)
我将内联样式更改为类,但是概念是相同的。
问题主要是无效的函数名称(getElementsByClass *名称*),试图设置不存在的属性(topbox.style.box-shadow
)
另外,您需要记住该函数返回一个集合,而不是单个元素,因此您需要使用[0]进行引用
请注意,在这种情况下,我建议您不要使用原始的js方法,我更喜欢使用jQuery,因为它更加简洁,一旦您超越了代码之类的简单条件,您将很高兴使用它
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句