如何跟踪 DOM 元素的 class 属性更改并将其应用于某些元素
How to track DOM element's class attribute changes and apply same on some element
我有一个 angularjs
组件,在组件中我有以下 HTML
<div id="panel" class="hide-div">
<div id="viewPort" class="hide-div">
...
</div>
</div>
有第三方javascript/jquery
库,我无法控制第三方库,第三方库从[=17=中删除了classhide-div
] 在某些服务器端事件上。
hide-div
class 隐藏元素。
现在我的要求是删除 hide-div
class 来自 panel
,当它从 viewPort
中删除时。简而言之,如果 viewPort
被隐藏,那么面板应该被隐藏,如果 viewPort
是可见的,那么 panel
也应该是可见的。
如果可能,连接到其他库以在 shows/hides div.
时从它那里获得主动通知
如果您做不到,您可以使用 mutation observer 来观察元素属性的变化,然后 show/hide 您的其他元素,具体取决于该元素是否具有相关 class.
示例:
// Your code
var observer = new MutationObserver(function() {
var source = $("#source");
var target = $("#target");
target.toggleClass("hide-div", source.hasClass("hide-div"));
});
observer.observe($("#source")[0], {attributes: true});
// This code emulates the library that you don't control
var handle = setInterval(function() {
$("#source").toggleClass("hide-div");
}, 800);
$("#btn-stop").on("click", function() {
clearInterval(handle);
});
.hide-div {
display: none;
}
<button id="btn-stop">Stop</button>
<div id="source">This is the source element that the library changes</div>
<div id="target">This is the target element that we update when the source element changes</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
我有一个 angularjs
组件,在组件中我有以下 HTML
<div id="panel" class="hide-div">
<div id="viewPort" class="hide-div">
...
</div>
</div>
有第三方javascript/jquery
库,我无法控制第三方库,第三方库从[=17=中删除了classhide-div
] 在某些服务器端事件上。
hide-div
class 隐藏元素。
现在我的要求是删除 hide-div
class 来自 panel
,当它从 viewPort
中删除时。简而言之,如果 viewPort
被隐藏,那么面板应该被隐藏,如果 viewPort
是可见的,那么 panel
也应该是可见的。
如果可能,连接到其他库以在 shows/hides div.
时从它那里获得主动通知如果您做不到,您可以使用 mutation observer 来观察元素属性的变化,然后 show/hide 您的其他元素,具体取决于该元素是否具有相关 class.
示例:
// Your code
var observer = new MutationObserver(function() {
var source = $("#source");
var target = $("#target");
target.toggleClass("hide-div", source.hasClass("hide-div"));
});
observer.observe($("#source")[0], {attributes: true});
// This code emulates the library that you don't control
var handle = setInterval(function() {
$("#source").toggleClass("hide-div");
}, 800);
$("#btn-stop").on("click", function() {
clearInterval(handle);
});
.hide-div {
display: none;
}
<button id="btn-stop">Stop</button>
<div id="source">This is the source element that the library changes</div>
<div id="target">This is the target element that we update when the source element changes</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>