如何使按钮更具反应性

问题描述 投票:0回答:1

如果我单击按钮的速度过快,则不会执行该操作,就好像没有注册该单击一样。有什么办法可以使这个简单的代码做出更好的反应?还是这差不多呢?任何建议都会对以后的小型项目有所帮助。

// function named change_color which contains color array and random selection
function change_Color(){
    // creating color variable equal to the color array
    var color = ["blue", "red", "green", "yellow"];
    // created random variable targeting the color variable saying to choose
    // a random color from the array
    var random = color[Math.floor(Math.random()*color.length)];
    // targets the the div element with id wrapper, telling it to use the
    // random variable
    document.getElementById("wrapper").style.backgroundColor = random;
}
body {
    margin: 0;
}
* {
    box-sizing: border-box;
}

#wrapper {
    width: 100%;
    height: 100vh;
    background-color: skyblue;
    display: flex;
    justify-content: center;
    align-items: center;

    button {
        padding: 10px;
        background: orange;
        color: white;
        border: none;
        border-radius: 10px;
        font-size: 2rem;
        transition: .5s ease;

        &:hover {
            box-shadow: 0 4px 3px 0px rgba(255, 255, 255, 0.8);
            cursor: pointer;
        }
        &:focus {
            outline: 0;
            color: skyblue;
        }
    }
    

}
<body>
    <div id="wrapper">
        <button onclick="change_Color()">Click me!</button>
    </div>
    <script src="JS/style.js"></script>
</body>
javascript button colors reactive
1个回答
0
投票

此时,您受硬件层的支配,但是您可以将不需要该函数中的任何代码移出该函数,从而减少了处理量。再说一次,您可能看不到任何改善,因为click触发了JavaScript运行时范围之外的操作,然后浏览器的代码又调用了操作系统代码,然后运行。

// The following two lines don't need to be invoked 
// over and over and could potentially speed things
// up by not being in the function.
var color = ["blue", "red", "green", "yellow"];
let wrapper = document.getElementById("wrapper");

// function named change_color which contains color array and random selection
function change_Color(){
    // There's no reason for a variable if you only use its value once:
    wrapper.style.backgroundColor = color[Math.floor(Math.random()*color.length)];
}
body {
    margin: 0;
}
* {
    box-sizing: border-box;
}

#wrapper {
    width: 100%;
    height: 100vh;
    background-color: skyblue;
    display: flex;
    justify-content: center;
    align-items: center;

    button {
        padding: 10px;
        background: orange;
        color: white;
        border: none;
        border-radius: 10px;
        font-size: 2rem;
        transition: .5s ease;

        &:hover {
            box-shadow: 0 4px 3px 0px rgba(255, 255, 255, 0.8);
            cursor: pointer;
        }
        &:focus {
            outline: 0;
            color: skyblue;
        }
    }
    

}
<body>
    <div id="wrapper">
        <button onclick="change_Color()">Click me!</button>
    </div>
    <script src="JS/style.js"></script>
</body>
© www.soinside.com 2019 - 2024. All rights reserved.