HTML - DOM style 屬性



HTML DOM 的style 屬性用於獲取直接為特定元素設定的 CSS 樣式。

它可以訪問該特定元素的內聯 CSS 屬性,不包括 <head> 部分或任何外部樣式表中的樣式。

語法

以下是 HTML DOM 的style(設定樣式)屬性的語法:

element.style.propertyName = value;

其中,“value”是您想要應用於特定元素 CSS 屬性的新值。

要獲取已使用的樣式屬性,請使用以下語法:

element.style.propertyName;

引數

此屬性不接受任何引數。

返回值

style 屬性返回一個物件,該物件包含應用於特定元素的內聯 CSS 樣式。

示例 1:將內聯樣式應用於段落元素

下面的程式演示瞭如何使用 HTML DOM 的style 屬性將樣式應用於段落 (<p>) 元素:

<!DOCTYPE html>
<html lang="en">
<head> 
<style> 
   .highlighted {
     background-color: lightblue;
     padding: 10px;
     border: 1px solid blue;
   }
   button{
       padding: 8px 10px;
   }
</style>
</head>
<body>
<p id="myPara">Click the below button to change my style!</p>
<button onclick="changeStyle()">Change Style</button>
<script>
   function changeStyle() {
      // Get the paragraph element
      let para = document.getElementById('myPara');
      
      // Apply new styles using the style property
      para.style.backgroundColor ='green';
      para.style.color = 'white';
      para.style.fontWeight = 'bold';
      para.style.padding = '15px';
      para.innerHTML = 'Style Changed!';
   }
</script>
</body>
</html>  

上面的程式在單擊按鈕時將樣式新增到段落 (“p”) 元素。

示例 2:每次單擊時更改段落的顏色

以下是 HTML DOM style 屬性的另一個示例。我們使用此屬性在單擊按鈕時更新段落 (“p”) 元素的文字顏色:

<!DOCTYPE html>
<html lang="en">
<head> 
<style>
   #colorfulText {
     font-size: 24px;
     font-weight: bold;
     margin-top: 20px;
   }
   button{
       padding: 8px 10px;
   }
</style>
</head>
<body>
<p>Click the below to update the style..</p>
<p id="colorfulText">Click the button to see colorful text!</p>
<button onclick="changeColor()">Generate Colorful Text</button>
<script>
   function changeColor() {
      let t=document.getElementById('colorfulText');
      let col= ['red','green','blue','orange','purple'];
      let randomColor = col[Math.floor(Math.random() * col.length)];
      t.style.color = randomColor;
      t.innerHTML = `Colorful Text in ${randomColor.toUpperCase()}`;
   }
</script>
</body>
</html>

上面的程式每次單擊按鈕時都會向段落新增新的顏色。

示例 3:將高亮效果應用於按鈕元素

在下面的示例中,DOM style 屬性用於透過在單擊時將高亮效果應用於按鈕來更改元素的外觀:

<!DOCTYPE html>
<html lang="en">
<head> 
<style>
   button{
       padding: 8px 10px;
       cursor: pointer;
   }
</style>
</head>
<body>
<p>Click the below button to add a highlight effect to it.<p> 
<button id="myButton">Click to Highlight</button>
<script>
   let bn = document.getElementById('myButton');
   //Add event listener to the button
   bn.addEventListener('click', function() {
      // Change the background color using style property
      bn.style.backgroundColor = 'green';
      bn.style.color = 'white';
      bn.style.border = 'none';
      bn.innerHTML = 'Highlighted!';
   });
</script>
</body>
</html> 

執行上述程式後,將顯示一個按鈕,單擊該按鈕時,將向該按鈕新增樣式。

支援的瀏覽器

屬性 Chrome Edge Firefox Safari Opera
style
html_dom_element_reference.htm
廣告