[英]I need to change the opacity value of an image using JavaScript when i mouse over it but my code isn't working
I need the images opacity to increase when I mouse over and decrease when I mouse out and I need this to be gradual and not instant as it would be with CSS.我需要图像不透明度在鼠标悬停时增加,鼠标移开时降低,我需要这是渐进的而不是像 CSS 那样即时的。
<html>
<head>
</head>
<body>
<img id="test" src="space1.png" onmouseover="updateOpacity()"/>
<script type="text/javascript">
var element = document.getElementById('test');
var opacity = element.style.opacity;
function updateOpacity()
{
opacity = opacity += 0.2;
if(opacity >= 1)
{
// done
opacity = 1;
}
else
{
element.style.opacity = opacity; // this updates the opacity
setTimeout(function(){updateOpacity();}, 50); // 50 is the delay, 50milliseconds
}
}
</stript>
</body>
</html>
If you don't need to support current IE, you can do this cleanly using CSS transitions :如果您不需要支持当前的 IE,您可以使用CSS transitions干净地做到这一点:
<img id="test" src="space1.png"/>
#test {
transition: opacity 600ms;
opacity: 0.35;
}
#test:hover {
opacity: 1.0;
}
Obligatory jsFiddle: http://jsfiddle.net/millimoose/uNeMg/强制性 jsFiddle: http : //jsfiddle.net/millimoose/uNeMg/
(For the sake of clarity and sanity I'm omitting the vendor prefixes and using -prefix-free
.) (为了清晰起见,我省略了供应商前缀并使用-prefix-free
。)
Is jQuery an option? jQuery 是一种选择吗?
<img id="test" src="space1.png" style="opacity: 0.1;">
<script>
var delay = 500; //500ms
$("#test").mouseover(function(){
$(this).stop().animate({
opacity: 1.0
}, delay);
}).mouseout(function(){
$(this).stop().animate({
opacity: 0.1
}, delay);
});
</script>
EDIT: http://jsfiddle.net/m3PAy/编辑: http : //jsfiddle.net/m3PAy/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.