[英]Detect changed style property?
我需要檢測 css 上的變化,但我需要樣式屬性(寬度、高度、背景顏色……等)作為變量,這意味着只有發生變化的那個。 所以我不需要價值。 我需要一個變量形式的樣式屬性,例如粗體:
document.getElementById ('id1')。 風格。 背景顏色= '紅色';
document.getElementById ('id1')。 風格。 顏色='紅色';
我嘗試使用 MutationObserver (也許是一些樣式過濾器)......或者也許還有其他方法如何獲取樣式屬性?
<h1 id="id1" style="background-color:green;color:blue;">My Heading 1</h1>
<button type="button"
onclick="document.getElementById('id1').style.color = 'yellow'">
Click Me!</button>
<button type="button"
onclick="document.getElementById('id1').style.backgroundColor = 'red'">
Click Me!</button>
const Observep = document.getElementById("id1");
const observerp = new MutationObserver(function() {
// var styleproperty = (backgroundColor or color or width....)
alert("id1 chenge" + styleproperty);
});
observerp.observe(Observep, {subtree: true, attributes: true});
嘗試這個,
<button type="button" onclick="addStyle()"> Click Me!</button>
<script type="text/javascript">
const elem = document.getElementById("id1");
var setStyle = {
backgroundColor:'green',
color:'blue',
}
function addStyle (){
for(let prop of Object.keys(setStyle)){
console.log(prop);
elem.style[prop.toString()] = setStyle[prop.toString()];
}
}
</script>
我相信這就是您正在尋找的:
const Observep = document.getElementById("id1"); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(mutation) { //console.log(mutation.target.style) let styles = mutation.target.style; for(style of styles){ console.log(style) } if(mutation.attributeName === 'style'){ alert("style change"); } }); }); // Notify me of style changes var observerConfig = { attributes: true, attributeFilter: ["style"] }; observer.observe(Observep, observerConfig);
<h1 id="id1" style="background-color:green;color:blue;">My Heading 1</h1> <button type="button" onclick="document.getElementById('id1').style.color = 'yellow'"> Click Me.</button> <button type="button" onclick="document.getElementById('id1').style.backgroundColor = 'red'"> Click Me!</button>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.