2

我有一个按钮和一个图像,并希望它们改变颜色onmouseover。按钮颜色变好:

<script>
function secondColor(x) {
x.style.color="#000000";
}
function firstColor(x) {
x.style.color="#ffaacc";
}
</script>

<input onmouseover="secondColor(this)" onmouseout="firstColor(this)" type="submit"><br>

我怎样才能对图像做同样的事情?有没有办法:

<img src="..." ...... 

或者我是否必须有第二张图像来替换第一个图像onmouseover,这是唯一的方法?

4

5 回答 5

2

如果您不太关心支持旧浏览器,您可以使用新的 CSS3 过滤器brightness。在 chrome 中,你可以这样写:

var image = document.getElementById('img');

image.addEventListener('mouseover', function() { 
    image.setAttribute('style','-webkit-filter: brightness(1.5)'); 
}, false);

image.addEventListener('mouseout', function() { 
    image.setAttribute('style','-webkit-filter: brightness(1.0)'); 
}, false);

不过,我不推荐这种方法。悬停时使用另一张图片将是更好的解决方案。

于 2013-09-12T22:28:13.107 回答
2

我知道这是旧的,但你不需要两个图像。使用一张图片查看我的示例。

您可以简单地更改背景图像的位置。

<div class="changeColor">&nbsp;</div>

JavaScript

var dvChange = document.getElementsByClassName('changeColor');

 dvChange[0].onmouseover = function(){
   this.style.backgroundPosition = '-400px 0px'; 
 }

dvChange[0].onmouseout = function(){
   this.style.backgroundPosition = '0px 0px'; 
}

CSS

.changeColor{
    background-image:url('http://www.upsequence.com/images/multibg.png');
    width:400px;
    height:400px;
    background-position: 0px 0px;
}

.changeColor:hover{
    background-image:url('http://www.upsequence.com/images/multibg.png');
    width:400px;
    height:400px;
    background-position: -400px 0px;
}

您还可以尝试更改图像 onmouseover 和 onmouseout 的不透明度。我没有这方面的例子,但它超级容易找到,我相信它已经在某个地方的堆栈交换中得到了回答。

在下面的 JSFiddle 中有 Javascript 和非 Javascript 示例。 http://jsfiddle.net/hallmanbilly/gtf2s8ts/

享受!!

于 2014-08-30T20:35:57.020 回答
1

您可以在鼠标悬停时更改图像 SRC,您可以加载两个图像并使用淡入淡出效果来“更改”它们。但更好的是,您可以使用图像作为 DIV 背景,制作精灵并将 BG 移动到鼠标上方。

加载两个不同的图像会使您在悬停和第二个图像加载时消失。最好不要使用 JS。从两个图像中制作精灵,将其作为DIV的BG并为DIV编写两个CSS,正常和悬停时。

于 2013-09-12T22:10:53.893 回答
1

我认为您必须使用第二张图片。我最近浏览了以下文章,描述了如何使用 css 在悬停时进行图像交叉淡化。交叉淡入淡出图像悬停效果

于 2013-09-12T22:12:36.943 回答
0

如果您有权访问 JQuery,请使用悬停功能。如果你想改变形象

$('#imageid').hover(function(){
    //change image or color or opacity
    $(this).attr('src', newImageSrc);
});

在文档准备功能中添加此功能。

于 2013-09-12T22:12:33.180 回答