按钮背景色切换 [英] Button background color toggle

查看:40
本文介绍了按钮背景色切换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试切换onClick按钮的背景色属性,但颜色只更改一次,并且不会来回切换。以下是代码。

function btnColor(btn, color) {
var property = document.getElementById(btn);
    if (property.style.backgroundColor == "rgb(244,113,33)") {
        property.style.backgroundColor=color;
    }
    else {
        property.style.backgroundColor = "rgb(244,113,33)";
    }
}

<input type="button" id="btnHousing" value="Housing" onclick="toggleLayer('transparent1');btnColor('btnHousing','rgb(255,242,0)');" />

推荐答案

您遇到的问题是,元素的background-color在浏览器中的报告方式不同,可以是十六进制的rgb、rgba(带或不带空格),也可以是hsl...

因此该按钮可能永远不会满足if条件,这意味着它将始终转到else

考虑到这一点,我建议使用类名来跟踪未切换/切换的状态:

function btnColor(btn, color) {
var property = document.getElementById(btn);
    if (property.className !== 'toggled') {
        property.style.backgroundColor=color;
        property.className = 'toggled'
    }
    else {
        property.style.backgroundColor = "rgb(244,113,33)";
        property.className = '';
    }
}

JS Fiddle demo

当然,如果我们使用元素的class,我们也可以使用样式元素:

function btnColor(btn) {
var property = document.getElementById(btn);
    if (property.className !== 'toggled') {
        property.className = 'toggled'
    }
    else {
        property.className = '';
    }
}

使用css:

#btnHousing {
    background-color: rgb(255,242,0);
}

#btnHousing.toggled {
    background-color: rgb(244,113,33);
}

JS Fiddle demo

可以将前面的JavaScript简化为(使用相同的CSS):

function btnColor(btn) {
    var property = document.getElementById(btn);
    property.className = 'toggled' == property.className ? '' : 'toggled';
}

JS Fiddle demo

这篇关于按钮背景色切换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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