我試過以下代碼:
<button id = "changeColor">Click here to change my color</button>
<script>
var changeButton = document.getElementById('changeColor');
function random(number){
return Math.floor(Math.random()*number);
}
function switchColor(){
var randomColor = 'rgb(' random(255) ',' random(255) ',' random(255) ')';
}
changeButton.addEventListener('click', switchColor);
</script>
但該按鈕在單擊時不會回傳任何顏色。
非常感謝您回答我的問題
uj5u.com熱心網友回復:
你需要改變color在style與genrated隨機顏色選擇按鈕。
changeButton.style.color = randomColor
<button id = "changeColor">Click here to change my color</button>
<script>
var changeButton = document.getElementById('changeColor');
function random(number){
return Math.floor(Math.random()*number);
}
function switchColor(){
var randomColor = 'rgb(' random(255) ',' random(255) ',' random(255) ')';
changeButton.style.color = randomColor
console.log(randomColor);
}
changeButton.addEventListener('click', switchColor);
</script>
uj5u.com熱心網友回復:
<button id = "changeColor">Click here to change my color</button>
<script>
var changeButton = document.getElementById('changeColor');
function random(number){
return Math.floor(Math.random()*number);
}
function switchColor(){
var randomColor = 'rgb(' random(255) ',' random(255) ',' random(255) ')';
// CHANGE THE TEXT COLOR
document.getElementById("changeColor").style.color = randomColor;
}
changeButton.addEventListener('click', switchColor);
</script>
uj5u.com熱心網友回復:
試試這個方法
您的代碼丟失
changeButton.style.color = color;
var changeButton = document.getElementById('changeColor');
function random(min, max){
return Math.floor(Math.random() * (max - min 1)) min;
}
function switchColor(){
var color;
color = 'rgb(' random(0, 255) ',' random(0, 255) ',' random(0, 255) ')';
changeButton.style.color = color;
}
changeButton.addEventListener('click', switchColor);
button{ border: none; }
<button id = "changeColor">Click here to change my color</button>
uj5u.com熱心網友回復:
為了保持更精確,試試這個
var changeButton = document.getElementById('changeColor');
changeButton.onclick= () => {
var randomColor = 'rgb(' Math.random()*255 ',' Math.random()*255 ',' Math.random()*255 ')';
changeButton.style.color = randomColor
}
<button id = "changeColor">Click here to change my color</button>
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/318163.html
標籤:javascript html dom dom事件
