在一行中编写JavaScript样式属性

tez616oj  于 2023-04-10  发布在  Java
关注(0)|答案(4)|浏览(111)

这可能是一个简单的问题。但我不知道如何做。这是我的js文件中的一个if语句。

if (splitStatus[0].includes("LIGHTS TURNED OFF")){

button2.style.background='#00FA9A' ; 
button2.style.color='   black'; 
button2.style.boxShadow=' 0 0 20px 2px rgba(0, 148, 254, 0.825)';

button1.style.background ="black";  
button1.style.color ="white"; 
button1.style.boxShadow='black';
  }

这只是我的if语句之一,我有很多if语句。有没有办法缩短这段代码?例如,在一行中应用所有样式到按钮1?并在一行中应用所有样式到按钮2?谢谢你的时间。
注意:我可以有超过20个按钮。S0的css类的每个按钮不会帮助

3htmauhk

3htmauhk1#

你仍然可以使用Object.assign来实现你的一行程序,并利用js对象的灵活性、可重用性和可变性来做一些难以想象的事情。

let styleObject = {color: '#fff', 'background-color' : '#000'};
Object.assign(buttonX.style, styleObject) ;
// modify styleObject as you like and reuse...
w1jd8yoj

w1jd8yoj2#

将不同的属性放入CSS中,并切换一个类。类似于:

.lights-off .button1 {
  background: black;
  color: white;
  box-shadow: 'black';
}
.lights-off .button2 {
  background: #00FA9A;
  color: black;
  box-shadow: 0 0 20px 2px rgba(0, 148, 254, 0.825);
}

然后您可以将原始代码更改为

if (splitStatus[0].includes("LIGHTS TURNED OFF")){
  container.classList.add('lights-off');
}

其中container是DOM中两个按钮的祖先。
WET JavaScript通常应该避免。WET CSS非常常见,它本身没有什么问题,尽管在某些情况下,使用SASS等预处理器可以减少重复性。

qvk1mo1f

qvk1mo1f3#

方案一

简而言之,我们将buttons作为objects动态添加到网页中,并为colorsbackgroundsbox-shadow提供一些键和值。
如果input选中,则使用每个button样式来设置它们的样式取决于它的value和每个objcet中的num键。如果未选中unset样式,或者您可以添加其他样式(objects中的keysvalues),以防您想要设置它们的样式。
所有你需要做的就是添加按钮!

  • 代码已注解,请查看 *
(function(){
    
    // Array To Hold HTML Output (The Buttons)
    let buttonsOutput = [];

    // Draw buttons function
    function drawButtons(){
        buttonsArray.forEach(button => {
            let btn = 
            `
            <button value="${button.num}" class="myBtn">${button.num}</button>
            `;

            buttonsOutput.push(btn);
        });

        buttonsContainer.innerHTML = buttonsOutput.join('');
    }

    // Get The Buttons Container
    let buttonsContainer = document.getElementById('buttons-container');

    // Array Of Buttons Objects
    let buttonsArray = [
        {num: "1", color: "red", background: "green", boxShadow: "0 0 1px 1px yellow"},
        {num: "2", color: "white", background: "purple", boxShadow: "0 0 1px 1px pinks"},
        {num: "3", color: "white", background: "red", boxShadow: "0 0 1px 1px black"},
        {num: "4", color: "green", background: "blue", boxShadow: "0 0 1px 1px gray"},
        {num: "5", color: "red", background: "green", boxShadow: "0 0 1px 1px orange"}
    ];

    // Run the function
    drawButtons();
    checkIfIncluded(buttonsArray);
})();

// Pass The Function To All Buttons To Set The New Style
function checkIfIncluded(arr){
    let myBtns = document.querySelectorAll('.myBtn');
    let input = document.getElementById('lights');

    // Add Event To The Input
    input.addEventListener('change', () => {
        // Loop Through The Buttons And The Array Of Buttons
        for(let i = 0; i < myBtns.length; i++){
            if(input.checked){
                // If Checked, Style it
                myBtns[i].style.color = arr[i].color;
                myBtns[i].style.background = arr[i].background;
                myBtns[i].style.boxShadow = arr[i].boxShadow;    
            } else {
                // If Not, UNSET The Style, Or You Can Add Another Colors To Set Them To In Case The Input Is Not Checked
                myBtns[i].style.color = 'unset';
                myBtns[i].style.background = 'unset';
                myBtns[i].style.boxShadow = 'unset';
            }
        }
    });
}
* {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        #buttons-container {
            display: flex;
            justify-content: center;
            margin: 20px 0;
        }

        .myBtn {
            width: 50px;
            height: 40px;
            margin: 0 10px;
        }

        #input-box {
            display: flex;
            justify-content: center;
            align-items: center;
            margin: 20px;
        }

        #input-box input {
            width: 30px;
            height: 30px;
        }
<div id="input-box">
            <input id="lights" type="checkbox">
        </div>
        <div id="buttons-container"></div>

溶液2

我们只在HTML页面中设置buttons的值(不管你叫什么attribute),并将class设置为loop,然后检查。解决方案1中的相同function用于检查是否已检查,并根据numvalue设置其样式。

// Array Of Buttons Objects
let buttonsArray = [
    {num: "1", color: "red", background: "green", boxShadow: "0 0 1px 1px yellow"},
    {num: "2", color: "white", background: "purple", boxShadow: "0 0 1px 1px pinks"},
    {num: "3", color: "white", background: "red", boxShadow: "0 0 1px 1px black"},
    {num: "4", color: "green", background: "blue", boxShadow: "0 0 1px 1px gray"},
    {num: "5", color: "red", background: "green", boxShadow: "0 0 1px 1px orange"}
];



function checkIfIncluded(arr){
    let myBtns = document.querySelectorAll('.myBtn');
    let input = document.getElementById('lights');

    // Add Event To The Input
    input.addEventListener('change', () => {
        // Loop Through The Buttons And The Array Of Buttons
        for(let i = 0; i < myBtns.length; i++){
            if(input.checked){
              // If checked, Style It
              myBtns[i].style.color = arr[i].color;
              myBtns[i].style.background = arr[i].background;
              myBtns[i].style.boxShadow = arr[i].boxShadow;    
            } else {
                // If Not, UNSET The Style, Or You Can Add Another Colors To Set Them To In Case The Input Is Not Checked
                myBtns[i].style.color = 'unset';
                myBtns[i].style.background = 'unset';
                myBtns[i].style.boxShadow = 'unset';
            }
        }
    });
}


// Run The Function
checkIfIncluded(buttonsArray);
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

#buttons-container {
    display: flex;
    justify-content: center;
    margin: 20px 0;
}

.myBtn {
    width: 50px;
    height: 40px;
    margin: 0 10px;
}

#input-box {
    display: flex;
    justify-content: center;
    align-items: center;
    margin: 20px;
}

#input-box input {
    width: 30px;
    height: 30px;
}
<div id="input-box">
    <input id="lights" type="checkbox">
</div>
<div id="buttons-container">
    <button value="1" class="myBtn">1</button>      
    <button value="2" class="myBtn">2</button>        
    <button value="3" class="myBtn">3</button>
    <button value="4" class="myBtn">4</button>  
    <button value="5" class="myBtn">5</button>
</div>
l3zydbqr

l3zydbqr4#

最好的方法是创建CSS类,然后在元素中添加/删除它。但是,如果你真的想把所有东西都封装在代码中,你可以使用元素样式的cssText属性来缩短代码:
例如

if (splitStatus[0].includes("LIGHTS TURNED OFF")){

   button2.style.cssText= "background: #00FA9A; color: black ; boxShadow: 0 0 20px 2px rgba(0, 148, 254, 0.825);";

   button1.style.cssText = "background: black; color: white; boxShadow:black;";
 
 }

更多信息:https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleDeclaration/cssText
示例:https://www.w3schools.com/jsref/prop_style_csstext.asp

相关问题