功能一:修改文檔的背景顏色
代碼:
<body>
<form>
<p align="left">請輸入顏色編碼:</p>
<input type="text"name="text" size="20" />
<input type="button" name="button" value="修改顏色" onClick="change(this.form)" />
</form>
<script language="JavaScript">
function change(form)
{
/*未輸入顏色編碼,彈出提示框*/
if (form.text.value == "")
alert("你喜歡的顏色是?");
else
{
/*按輸入顏色編碼,修改背景顏色*/
document.bgColor=(""+form.text.value+" ");
}
}
</script>
</body>
相關知識點
document顏色相關的屬性如下:
bgColor:背景色
fgColor:前景色(文字顏色)
linkColor/alinkColor/vlinkColor: 鏈接色
可利用for(var x in document) { console.log(x)}
命令在控制檯查詢document的全部屬性
功能二:修改某個自定義標籤的背景顏色
代碼:
<!-- 使用方法一 -->
<input id="input1" type="text">
<input id='button1' type="button" value="Button1">
<div id="box1" style="width: 100px; height: 100px; background-color: black;"></div>
<!-- 使用方法二 -->
<input id="input2" type="text">
<input id='button2' type="button" value="Button2">
<br>
<canvas id="box2" width="100" height="100" style="background-color: black;"></canvas>
<script>
// 方法一
const input1 = document.querySelector('#input1');
const button1 = document.querySelector('#button1');
const box1 = document.querySelector('#box1');
button1.onclick = function() {
if(input1.value === '') {
alert('請輸入你喜歡的顏色!');
} else {
box1.style.backgroundColor = input1.value;
}
}
// 方法二
const input2 = document.querySelector('#input2');
const button2 = document.querySelector('#button2');
const box2 = document.querySelector('#box2');
button2.onclick = function() {
if(input2.value === '') {
alert('請輸入你喜歡的顏色!');
} else {
const ctx = box2.getContext('2d');
ctx.fillStyle = input2.value;
ctx.fillRect(0,0,100,100);
}
}
</script>
知識點
box1.style.backgroundColor = input1.value;
獲取HTML節點後,利用節點的style屬性裏面的backgroundColor屬性修改backgroundColor的值,便修改了box1的背景色。
可以使用Object.getPrototypeOf(box1)
查看box1包含的屬性。
const ctx = box2.getContext('2d');
獲取HTML節點的2d環境對象
ctx.fillStyle = input2.value;
填充樣式,canvas 的fillStyle可以填充純色,漸變和模式
ctx.fillRect(0,0,100,100);
繪製矩形並填充
更多實例,可訪問:https://github.com/956159241/JSExamples
如果文章能夠對您有所幫助,我便感到十分榮幸。如若文章能被您點贊,那便是萬分榮幸~