2017-04-01 72 views
-1

說我有一個CSS聲明使用JS修改在CSS文件中聲明的屬性。

.example { 
    height: 60px; 
} 

是否有使用Javascript功能來修改60px的方法嗎?

比方說,

function updateHeight() { 
    // add 10px to the css class `example`; 
} 

所以CSS類將有效地成爲

.example { 
    height: 70px; 
} 
+0

http://stackoverflow.com/questions/ 43153407 /顯示移動 - 分量 - reactjs – Piyush

回答

2

您可以使用這樣的代碼:

document.querySelector('.test').style.height = '150px';
.test { 
 
    width : 100px; 
 
    height : 100px; 
 
    background : #0AF; 
 
}
<div class="test"></div>

當然,您始終有機會使代碼儘可能抽象。

在例子中,你可以有一個可以工作的這樣的一個功能:

// Responsible to set the CSS Height property of the given element 
function changeHeight(selector, height) { 
    // Choose the element should get modified 
    var $element = document.querySelector(selector); 
    // Change the height proprety 
    $element.style.height = height; 
} 

changeHeight('.test', '150px'); 

,或者你可以去更抽象的那樣:

// Responsible to modify the given CSS property of the given 
// HTML element 
function changeCssProperty(selector, property, value) { 
    // Find the given element in the DOM 
    var $element = document.querySelector(selector); 
    // Set the value to the given property 
    $element.style[property] = value; 
} 

changeCssProperty('.test', 'width', '200px');