使用javascript按下更改时执行某些操作

时间:2017-01-11 06:05:12

标签: javascript css

我制作了一些代码来生成RGB颜色,但它在更改后有效,但我希望在更改时执行此操作:

<input type="range" id="myNumber" min="0" max="255" onchange="myFunction()" value="0" />
<input type="range" id="myNumber2" min="0" max="255" onchange="myFunction()" value="0" />
<input type="range" id="myNumber3" min="0" max="255" onchange="myFunction()" value="0" />
<p id="demo">Blalalalala</p>

<script>
function myFunction() {
    var x = document.getElementById("myNumber").value;
    var y = document.getElementById("myNumber2").value;
    var z = document.getElementById("myNumber3").value;  
    document.getElementById("demo").style.transition = 'background 0.5s ease 0s';
    document.getElementById("demo").style.background = 'rgb('+x+','+y+','+z+')';
}
</script>

UPDATE!

回答我的不足之处,如果有人需要,这里是完整的代码

 <p>R (Stands for red):
    <input type="range" id="myNumber" min="0" max="255" step="1" oninput="myFunction()" value="0" /></p>
    <p>G (Stands for green):
    <input type="range" id="myNumber2" min="0" max="255" step="1" oninput="myFunction()" value="0" /></p>
    <p>B (Stands for blue):
    <input type="range" id="myNumber3" min="0" max="255" step="1" oninput="myFunction()" value="0" /></p>
    <p>A (Stands for opacity):
    <input type="range" id="myNumber4" min="0" max="1" step="0.1" oninput="myFunction()" value="1" /></p>




    <p id="demo">sasasasa</p>

    <script>
    document.getElementById("demo").style.background = 'rgb(0,0,0,1)';
    function myFunction() {
        var x = document.getElementById("myNumber").value;
        var y = document.getElementById("myNumber2").value;
        var z = document.getElementById("myNumber3").value; 
        var a = document.getElementById("myNumber4").value;     
        document.getElementById("demo").style.transition = 'background 0.5s ease 0s';
        document.getElementById("demo").style.background = 'rgba('+x+','+y+','+z+','+a+')';
    }
    </script>

2 个答案:

答案 0 :(得分:2)

使用HTML5 input事件代替change事件。

<input type="range" id="myNumber" min="0" max="255" oninput="myFunction()" value="0" />
<input type="range" id="myNumber2" min="0" max="255" oninput="myFunction()" value="0" />
<input type="range" id="myNumber3" min="0" max="255" oninput="myFunction()" value="0" />




<p id="demo">Blalalalala</p>

<script>
  function myFunction() {
    var x = document.getElementById("myNumber").value;
    var y = document.getElementById("myNumber2").value;
    var z = document.getElementById("myNumber3").value;
    document.getElementById("demo").style.transition = 'background 0.5s ease 0s';
    document.getElementById("demo").style.background = 'rgb(' + x + ',' + y + ',' + z + ')';
  }
</script>

检查browser compatibility of input event

答案 1 :(得分:2)

只有在用户释放鼠标时才会触发

onchange。要获得持续更新,您应该使用oninput事件,该事件将通过鼠标和键盘捕获Firefox,Safari和Chrome中的实时更新。

但是,IE10不支持oninput,所以最好的办法是组合两个事件处理程序,如下所示:

<input type="range" id="myNumber" min="0" max="255" onchange="myFunction()" oninput="myFunction()" value="0" />