没有jQuery的onmouseover过渡效果

时间:2012-10-23 21:29:06

标签: javascript html css

我使用onmouseover在我的开发网站http://www.new.ianroyal.co上悬停主网站徽标的效果。

onmouseover瞬间更改了站点徽标图像,我想知道是否可以在不使用jQuery的情况下应用转换效果(淡入或者通常只是降低转换速度)。

这是我的代码:

<a href="<?php echo esc_url( home_url( '/' ) ); ?>" ONMOUSEOVER='ian.src="http://new.ianroyal.co/wp-content/themes/twentytwelve/images/IN-Logo.png" ' ONMOUSEOUT='ian.src="http://new.ianroyal.co/wp-content/themes/twentytwelve/images/IN-Logo1.png"'>
  <img src="http://new.ianroyal.co/wp-content/themes/twentytwelve/images/IN-Logo1.png" NAME="ian" class="header-image" alt="Ian Nelson" />
</a>

我已经搜索过并搜索过,但似乎唯一的解决方案是jQuery,我还没有足够的把握。

谢谢

5 个答案:

答案 0 :(得分:3)

您可以使用纯CSS3。

.fade {
opacity: 1;
transition: opacity .25s ease-in-out;
-moz-transition: opacity .25s ease-in-out;
-webkit-transition: opacity .25s ease-in-out;
}

.fade:hover {
  opacity: 0.5;
  }

取自here的示例。还有很多其他的可能性,但这应该是一个良好的开端。

但是,它只适用于支持CSS3 Transitions的浏览器。 Internet Explorer尤其是late to the game,并且仍有lots of people out there using it(以及其他不支持CSS3的浏览器的旧版本)。

如果您想要一个真正的跨浏览器解决方案,最大限度地支持旧版本,那么JQuery真的是要走的路。无论看起来多么艰难,投入学习褪色的时间都会得到回报。几乎可以肯定,学习如何做一些JQuery比做一个等效的纯JavaScript解决方案更容易,这个解决方案可以提供与JQuery免费提供的相同的跨浏览器兼容性。

答案 1 :(得分:3)

使用css3过渡。

div {
    height: 100px;
    width: 100px;
    background: url(image1.png) no-repeat;
    -webkit-transition: all .3s ease-in-out;
    -moz-transition: all .3s ease-in-out;
}

div:hover {
    background-image: url(image2.png)
}

旧浏览器根本不会为转换设置动画。

演示: http://jsfiddle.net/elclanrs/jg7G3/

答案 2 :(得分:1)

理想情况下,只需使用CSS Transitions和:hover选择器,并将JS完全保留,comme ça

答案 3 :(得分:0)

学习jQuery。我保证它会让你在长期(和短期)跑步中幸福。话虽如此,一旦你了解了jQuery,就可以重新回到vanilla js中,这样你才能真正理解它是如何工作的。

例如,你在jquery中的问题就像:

一样简单
$(function() {
    $('a').fadeOut();
    $('a').attr('src', '{new image path}');
    $('a').fadeIn();
});

答案 4 :(得分:0)

工作示例,只需在同一目录中提供image1.jpg和image2.jpg:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.js" type="text/javascript"></script>
<script>
$(function() {

$('img').mouseenter(function(){
  $(this).fadeOut('fast', function(){
    $(this).attr('src', $(this).data('on'));
    $(this).fadeIn();
  });
});

$('img').mouseleave(function(){
  $(this).fadeOut('fast', function(){
    $(this).attr('src', $(this).data('off'));
    $(this).fadeIn();
  });
});


});

</script>

<img width="100" height="100" src="image1.jpg" data-on="image2.jpg" data-off="image1.jpg">
相关问题