我正在创建一个简单的chrome扩展程序。当DOM上存在某个元素时,我想应用一些样式规则。在检查了我要应用该修改的网站后,我发现感兴趣的元素仅在某些页面上创建,并且不在网站上的任何地方。如何使用jquery应用这些规则? 这是我正在测试但没有成功的代码:
(function($){
$(document).ready(function(){
var el = $('.e-overlay--adblock');
if(el.length){
el.css({'opacity':'0'});
console.log('Extension Started!');
}
});
}(jQuery));
我也尝试过这种解决方案,但没有成功:
我认为问题还在于元素.e-overlay .e-overlay__modal .e-overlay--full .e-overlay--adblock
的类
$(document).ready(function(){
var el = $('.e-overlay')[0];
// Create an observer instance linked to the callback function
var observer = new MutationObserver(function(){
el.css({'opacity':'0'});
console.log('Extension Started!');
});
// Start observing the target node for configured mutations
observer.observe(el, config);
// Later, you can stop observing
observer.disconnect();
});
变异观察者会给我这个错误:
未捕获的TypeError:无法在“ MutationObserver”上执行“观察”:参数1的类型不是“节点”。
答案 0 :(得分:1)
(function(win) {
'use strict';
var listeners = [],
doc = win.document,
MutationObserver = win.MutationObserver || win.WebKitMutationObserver,
observer;
function ready(selector, fn) {
// Store the selector and callback to be monitored
listeners.push({
selector: selector,
fn: fn
});
if (!observer) {
// Watch for changes in the document
observer = new MutationObserver(check);
observer.observe(doc.documentElement, {
childList: true,
subtree: true
});
}
// Check if the element is currently in the DOM
check();
}
function check() {
// Check the DOM for elements matching a stored selector
for (var i = 0, len = listeners.length, listener, elements; i < len; i++) {
listener = listeners[i];
// Query for elements matching the specified selector
elements = doc.querySelectorAll(listener.selector);
for (var j = 0, jLen = elements.length, element; j < jLen; j++) {
element = elements[j];
// Make sure the callback isn't invoked with the
// same element more than once
if (!element.ready) {
element.ready = true;
// Invoke the callback with the element
listener.fn.call(element, element);
}
}
}
}
// Expose `ready`
win.ready = ready;
})(this);
和用法:
ready('.e-overlay--adblock', function(element) {
// do something
});
答案 1 :(得分:0)
我找到了解决该问题的方法。经过一些调试和各种代码替代测试之后,我尝试仅在display
上设置none
属性。这行得通,但我不喜欢它作为解决方案。
(function($){
$(document).ready(function(){
var el = $('.e-overlay--full');
if(el.length){
console.log('Extension Started!');
setTimeout(function(){
el.css({'display':'none'});
}, 1000);
}
});
}(jQuery));
为确保不会显示模式,我还注入了css规则以消除不透明度:
.e-overlay--full{
opacity: 0 !important;
}