js改變style樣式和css樣式的簡單實例
js可實現(xiàn)用戶對頁面中的選擇條件改變頁面中的樣式,頁面樣式可以通過style修飾,也可以通過css修飾,先來看一下js改變style樣式,代碼如下:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Change.html</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
<script language="javascript">
function test4(event) {
if(event.value == "黑色") {
//獲取div1
var div1 = document.getElementById('div1');
div1.style.backgroundColor="black";
}
if(event.value == "紅色") {
//獲取div1
var div1 = document.getElementById('div1');
div1.style.backgroundColor="red";
}
}
</script>
</head>
<body>
<div id="div1" style="width:400px; height:300px; background-color:red;">div1</div>
<input type="button" value="黑色" onclick="test4(this)"/>
<input type="button" value="紅色" onclick="test4(this)"/>
</body>
</html>
test4(this)代表當(dāng)前的<input相當(dāng)于把它看成一個對象。
再來看一下改變css樣式,代碼如下:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Change1.html</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="css/Change.css">
<script language="javascript">
function test4(event) {
//獲取樣式表中所有class選擇器都獲得
var ocssRules = document.styleSheets[0].rules;
//從ocssRules中取出你希望的class
var style1 = ocssRules[0];
if(event.value == "黑色") {
//window.alert(style1.style.backgroundColor);
style1.style.backgroundColor="black";
}else if(event.value == "紅色") {
style1.style.backgroundColor="red";
}
}
</script>
</head>
<body>
<div id="div1" class="style1">div1</div>
<input type="button" value="黑色" onclick="test4(this)"/>
<input type="button" value="紅色" onclick="test4(this)"/>
</body>
</html>
以上就是小編為大家?guī)淼膉s改變style樣式和css樣式的簡單實例全部內(nèi)容了,希望大家多多支持腳本之家~
相關(guān)文章
深入理解JavaScript系列(26):設(shè)計模式之構(gòu)造函數(shù)模式詳解
這篇文章主要介紹了深入理解JavaScript系列(26):設(shè)計模式之構(gòu)造函數(shù)模式詳解,本文講解了基本用法、構(gòu)造函數(shù)與原型、只能用new嗎?、強制使用new、原始包裝函數(shù)等內(nèi)容,需要的朋友可以參考下2015-03-03
Javascript實現(xiàn)簡易天數(shù)計算器
這篇文章主要為大家詳細(xì)介紹了Javascript實現(xiàn)簡易天數(shù)計算器,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2020-05-05
6種JavaScript判斷對象自身為空的方法小結(jié)
這篇文章主要為大家詳細(xì)介紹了6種JavaScript判斷對象自身為空的方法,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2023-12-12
微信小程序?qū)崿F(xiàn)跟隨菜單效果和循環(huán)嵌套加載數(shù)據(jù)
這篇文章主要為大家詳細(xì)介紹了微信小程序?qū)崿F(xiàn)跟隨菜單效果和循環(huán)嵌套加載數(shù)據(jù),具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-11-11
前端本地數(shù)據(jù)存儲的幾種常見方式總結(jié)
在前端開發(fā)中,本地數(shù)據(jù)存儲是實現(xiàn)客戶端數(shù)據(jù)持久化的關(guān)鍵技術(shù),以下是幾種常見的前端本地數(shù)據(jù)存儲方式,通過代碼示例講解的非常詳細(xì),需要的朋友可以參考下2025-01-01
關(guān)于 byval 與 byref 的區(qū)別分析總結(jié)
關(guān)于 byval 與 byref 的區(qū)別分析總結(jié)...2007-10-10

