问题分析:根据提供的代码,需要操作iframe内部的DOM元素,特别是body和p标签,并创建事件。
解决方案:以下是操作iframe内部DOM的JavaScript代码:
// 1. 等待页面加载完成
window.addEventListener('load', function () {
// 获取TinyMCE编辑器中的iframe
const editorIframe = document.getElementById('editor-answer_ifr');
if (editorIframe) {
// 确保iframe已加载
if (editorIframe.contentDocument) {
manipulateEditorIframe(editorIframe);
} else {
editorIframe.addEventListener('load', function () {
manipulateEditorIframe(editorIframe);
});
}
}
});
// 2. 在函数中编写代码
function manipulateEditorIframe(iframe) {
try {
// 2.1 获取元素
const iframeDoc = iframe.contentDocument || iframe.contentWindow.document
const iframeBody = iframeDoc.body
console.log(iframeDoc)
// 2.2 改变样式或者是事件
console.log('成功操作了TinyMCE编辑器的iframe')
} catch (error) {
console.error('操作TinyMCE编辑器iframe时出错:', error)
}
}更多参考
// 等待页面加载完成
document.addEventListener('DOMContentLoaded', function () {
// 获取iframe元素
const iframe = document.getElementById('editor-answer_ifr');
// 检查iframe是否已加载
if (iframe.contentDocument) {
initIframeOperations(iframe);
} else {
// 如果iframe尚未加载,等待其加载完成
iframe.addEventListener('load', function () {
initIframeOperations(iframe);
});
}
});
function initIframeOperations(iframe) {
try {
// 获取iframe内部的document对象
const iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
// 获取iframe内部的body元素
const iframeBody = iframeDoc.body;
// 获取所有p标签
const pElements = iframeBody.getElementsByTagName('p');
// 为每个p标签添加点击事件
for (let i = 0; i < pElements.length; i++) {
pElements[i].addEventListener('click', function () {
console.log('点击了iframe内的p标签: ', this.textContent);
// 在这里添加您需要执行的操作
});
}
// 为body添加事件监听
iframeBody.addEventListener('keydown', function (e) {
console.log('在iframe内按下了键: ', e.key);
});
// 修改iframe内body的样式
iframeBody.style.backgroundColor = '#f9f9f9';
iframeBody.style.padding = '10px';
// 修改所有p标签的样式
for (let i = 0; i < pElements.length; i++) {
pElements[i].style.margin = '5px 0';
pElements[i].style.padding = '3px';
pElements[i].style.borderLeft = '2px solid #3498db';
}
console.log('成功操作了iframe内部的DOM元素');
} catch (error) {
console.error('操作iframe内部DOM时出错:', error);
}
}作者:霍欣标,如若转载,请注明出处:https://www.bigengwu.cn/shu/321.html