更改悬停按钮的图像? [英] Changing image for button on hover?

查看:55
本文介绍了更改悬停按钮的图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个HTML按钮,其设置如下:

Hi I have a HTML button that is setup like this:

<input type="image" src="derp.png">

由于未通过CSS分配图片,我应该如何在悬停时对其进行更改?

As the image is not assigned via CSS how am I meant to change it on hover?

推荐答案

类似下面的方法可以工作(尽管目前未经测试),但它要求将备用图像存储在自定义data-*属性中,以便脚本知道在哪里找到它,然后将原始src存储在类似的data-*中,以便将其放回mouseout上:

Something like the following would work (though currently untested), it requires the alternate image to be stored in a custome data-* attribute in order that the script knows where to find it, and then stores the original src in a similar data-* in order to put it back on mouseout:

var inputs = document.getElementsByTagName('input');

for (var i = 0, len = inputs.length; i < len; i++) {
    input = inputs[i];
    input.onmouseover = function(){
        this.setAttribute('data-orig-image',this.getAttribute('src'));
        this.src = this.getAttribute('data-alt-image');
    };
    input.onmouseout = function(){
        this.src = this.getAttribute('data-orig-image');
    };
}​

JS Fiddle演示.

请记住,以上要求您的input具有HTML表单:

Bear in mind the above requires your input to have the HTML form:

<input type="image" src="http://path.to/default/image.png" data-alt-image="http://path.to/mouseover/image.png" />​


已编辑以添加CSS选项,不幸的是,该选项并不完美,并且要求inputsrc属性中未设置图片:


Edited to add a CSS option, which is somewhat imperfect unfortunately, and requires that the input has no image set in its src attribute:

input[type=image] {
    background-image: url(http://davidrhysthomas.co.uk/img/dexter.png);
    background-repeat: no-repeat;
    background-position: 50% 50%;
    width: 200px;
    height: 185px;
}
input[type=image]:hover,
input[type=image]:active,
input[type=image]:focus {
    background-image: url(http://davidrhysthomas.co.uk/img/mandark.png);
}​

JS小提琴演示.

这篇关于更改悬停按钮的图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆