jQuery - 改变点击和悬停

时间:2014-05-30 20:19:09

标签: jquery html

我有5种不同的img标签,每个标签有四种不同的状态: on on-hover off 离悬停即可。所有这些都有一个相应的src,我用jQuery改变,所以共有20个不同的png文件。这一切都运行正常,当我在每个img标签旁边有文本需要根据它旁边的img标签改变颜色时,问题就出现了。如果单击或悬停文本,我还需要更改img标记。

HTML代码:

<div class="sheilds">
    <img class="sheild_icon" id="icon1" src="../img/icon1-on.png"  />
    <img class="sheild_icon" id="icon2" src="../img/icon2-on.png" />
    <img class="sheild_icon" id="icon3" src="../img/oxicon-on.png" />
    <img class="sheild_icon" id="icon4" src="../img/icon4-on.png" />
    <img class="sheild_icon" id="icon5" src="../img/icon5-on.png" />
</div>

<div class="text_pannel">
    <div class="icon_text" id="text_icon1"><p>Outdoors</p></div>
    <div class="icon_text" id="text_icon2"><p>Groups</p></div>
    <div class="icon_text" id="text_icon3"><p>Icons</p></div>
    <div class="icon_text" id="text_icon4"><p>Sports</p></div>
</div>

JavaScript / JQuery代码:

$(".sheild_icon")
    .mouseover(function() {
        this.src = this.src.replace('.png', '-hover.png');
    })
    .mouseout(function() {
        this.src = this.src.replace('-hover.png', '.png');
    })
    .click(function() {
        if (this.src.indexOf('-on') > -1) this.src = this.src.replace(/(.*)-on(.*)/, "$1-off$2");
        else this.src = this.src.replace(/(.*)-off(.*)/, "$1-on$2");
    }
);

Here is my fiddle

2 个答案:

答案 0 :(得分:0)

怎么样:

为这些文本元素添加和删除不同的类。

http://jsfiddle.net/Ca2Kn/1/

<script type="text/javascript">
$(".sheild_icon")
    .mouseover(function() {
        this.src = this.src.replace('.png', '-hover.png');
        $('#text_'+this.id).addClass('active');
    })
    .mouseout(function() {
        this.src = this.src.replace('-hover.png', '.png');
        $('#text_'+this.id).removeClass('active');
    })
    .click(function() {
        if (this.src.indexOf('-on') > -1) {
            this.src = this.src.replace(/(.*)-on(.*)/, "$1-off$2");
            $('#text_'+this.id).addClass('active2');
        }
        else {
            this.src = this.src.replace(/(.*)-off(.*)/, "$1-on$2");
            $('#text_'+this.id).removeClass('active2');
        }
    }
);
</script>


<style type="text/css">
.active,
.active2 {
    color:red;
    font-size:20px;
}
</style>

答案 1 :(得分:0)

你应该真的使用CSS来做到这一点。

<div class="icon_text" id="text_icon1"><p>Outdoors</p></div>

变为:

<div class="icon1"> Outdoors</div>

CSS:

.icon1 {
    background-image:url(/img/icon1-on.png);
    background-repeat:no-repeat;
    height:20px;
    padding-left:20px;
}

.icon1:hover {
    background-image:url(/img/icon1-hover.png);
}

.icon1.active {
    background-image:url(/img/icon1-off.png);
    color:#f00;
}

JS:

$(".sheild_icon").on('click', function() {$(this).addClass('active')});