简体   繁体   English

创建具有特定 css 的 div 时如何执行函数?

[英]How can I execute a function when a div with a particular css is created?

I am developing a tampermonkey script, in order to fill a popup when this appears, this in particular.我正在开发一个 tampermonkey 脚本,以便在出现时填充弹出窗口,特别是这个。

So when the page is launched and I click a button, this creates a new popup that is a div with a particular class.因此,当页面启动并单击一个按钮时,这会创建一个新的弹出窗口,该弹出窗口是具有特定类的 div。

The idea is that when this popup is launched execute a piece of code to fill that popup.这个想法是当这个弹出窗口被启动时执行一段代码来填充那个弹出窗口。

I am triying with the following code:我正在尝试使用以下代码:

/ ==UserScript==
// @name         New Userscript
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match        
// @icon         https://www.google.com/s2/favicons?domain=atlassian.net
// @grant        none
// ==/UserScript==

(function() {
    'use strict';
    document.getElementById('jira-dialog-heading').addEventListener('click', function() {
        alert('do something');
    });

})();

but doesn't work.但不起作用。

How can I do this?我怎样才能做到这一点?

EDIT 1编辑 1

All code updated更新了所有代码

Not errors in console不是控制台中的错误

Thanks谢谢

I would use mutationObserver to accomplish it: https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver/observe我会使用mutationObserver来完成它: https : //developer.mozilla.org/en-US/docs/Web/API/MutationObserver/observe

from MDN:来自 MDN:

The MutationObserver method observe() configures the MutationObserver callback to begin receiving notifications of changes to the DOM that match the given options. MutationObserver 方法 observe() 配置 MutationObserver 回调以开始接收与给定选项匹配的 DOM 更改通知。

From the above comment ...从上面的评论...

"There are two options. 1st) The OP owns the script and/or can subscribe to the popup launch process/event. In this case the OP can write and/or hook custom event handling code. 2nd) The OP does not own the script and/or can not subscribe to the popup launch process/event. In this case the OP needs to make use of a MutationObserver ." “有两种选择。1st)OP拥有脚本和/或可以订阅弹出启动过程/事件。在这种情况下,OP可以编写和/或挂钩自定义事件处理代码。2nd)OP不拥有脚本和/或无法订阅弹出启动过程/事件。在这种情况下,OP 需要使用MutationObserver 。”

The next provided code targets the second scenario and tries to cover the many possible but reasonable ways of how a popup could mutate the DOM ...下一个提供的代码针对第二种情况,并试图涵盖许多可能但合理的弹出窗口如何改变 DOM 的方法......

 // custom specific popup handling function handlePopupShow(popupNode) { console.log('handle popup show :: node ...', popupNode); } function handlePopupHide(popupNode) { console.log('handle popup hide :: node ...', popupNode); } // The popup specific mutation handler, the observers callback function. function handleChildNodeAndClassNameMutation(mutationList/*, observer*/) { mutationList.forEach(mutation => { const { type, attributeName } = mutation; if (type === 'attributes' && attributeName === 'class') { const { target } = mutation; if (target.matches('.popup-specific-name.show')) { handlePopupShow(target); } else if ( target.matches('.popup-specific-name.hide') || target.matches('.popup-specific-name:not(.show)') ) { handlePopupHide(target); } } else if (type === 'childList') { const { addedNodes: [ addedTargetNode ], removedNodes: [ removedTargetNode ], } = mutation; if ( addedTargetNode?.matches?.('.popup-specific-name') // addedTargetNode?.matches?.('.popup-specific-name.show') ) { handlePopupShow(addedTargetNode); } else if ( removedTargetNode?.matches?.('.popup-specific-name') ) { handlePopupHide(removedTargetNode); } } }); } // - The to be observed target node. // - Due to detecting a popup specifc element // it has to be the `document.body`. const popupMutationTarget = document.body; // Defines the to be observed popup specific mutations. const popupMutationConfig = { attributeFilter: ['class'], childList: true, subtree: true, }; // Create mutation observer. const popupObserver = new MutationObserver(handleChildNodeAndClassNameMutation); // // Start target node observation for popup specific mutations. // popupObserver.observe(popupMutationTarget, popupMutationConfig); // // Does stop the observation. // popupObserver.disconnect(); // bring test case to life. function togglePermanentPopup(/* evt */) { document .querySelector('.popup-specific-name.permanent') .classList.toggle('show'); } function toggleNonPermanentPopup(/* evt */) { let popupNode = document.querySelector('.popup-specific-name.non-permanent'); if (popupNode) { popupNode.remove(); } else { popupNode = document.createElement('div'); popupNode.classList.add('popup-specific-name', 'non-permanent'); popupNode.textContent = 'non permanent dom element, show and hide by insert and remove'; document.body.prepend(popupNode); } } document .querySelector('#toggle_permanent_popup') .addEventListener('click', togglePermanentPopup); document .querySelector('#toggle_non_permanent_popup') .addEventListener('click', toggleNonPermanentPopup); let inObservation = false; function toggleObservation({ target }) { if (inObservation) { // Does stop the observation. popupObserver.disconnect(); target.textContent = 'Start observation'; console.log('+++ Observer disconnected +++'); } else { // Start target node observation for popup specific mutations. popupObserver.observe(popupMutationTarget, popupMutationConfig); target.textContent = 'Stop observation'; console.log('+++ Observer is running +++'); } inObservation = !inObservation; } document .querySelector('#toggle_observation') .addEventListener('click', toggleObservation);
 .popup-specific-name { display: block; position: absolute; top: 0; width: 100%; text-align: center; background-color: #cf0; } .popup-specific-name.permanent { display: none; background-color: #fc0; } .popup-specific-name.show { display: unset; } .popup-specific-name + .popup-specific-name { top: 20px; } button { display: block; position: relative; top: 35px; } button#toggle_observation { float: right; top: 14px; } .as-console-wrapper { max-height: 111px!important; }
 <div class="popup-specific-name permanent"> permanent dom element, class name controlled show and hide </div> <button id="toggle_permanent_popup">toggle permanant popup</button> <button id="toggle_non_permanent_popup">toggle non permanant popup</button> <button id="toggle_observation">Start observation</button>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何获取在cshtml中使用循环创建的每个div / li / a的特定元素的Id - How can I get the Id of the particular element of each div / li / a that is created using loop in cshtml 当擦除() function 完成时,我如何执行 type() function - How can i Execute type() function when erase() function completes 我如何使用 JQuery 像 chrome 一样实现复制 css 选择器来截取特定 div 的屏幕截图 - how can I implement copy css selector as like chrome using JQuery to take screenshot of particular div 当我有多个具有相同类的div时,我怎么能只在div上执行动作 - How can i execute the action only on the div,when i have multiple div with same class 当使用 CSS 选中复选框时,如何切换 div 的可见性? - How can I toggle the visibility of a div when a checkbox is checked with CSS? 如何将现有CSS类样式应用于动态创建的div? - How can I apply an existing CSS class style to a dynamically created div? 单击元素时如何执行外部函数? - How can I execute an external function when an element is clicked? 加载页面时如何随机执行 JavaScript function ? - How can I execute a JavaScript function at random when the page is loaded? 当函数中存在“ for循环”时,如何使回调正确执行? - How can I get a callback to execute properly when there is a “for loop” in a function? 按下回车键时如何执行JavaScript函数 - How can I execute JavaScript function when the enter key is pressed
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM