此问题的解决方法是在子域中添加一段 JavaScript 代码来处理此问题。假设您的 iframe 具有 ID“my-iframe”,以下是解决方法的代码示例:
var myIframe = document.getElementById('my-iframe');
if (myIframe) {
// Add event listener for when the iframe is loaded
myIframe.addEventListener('load', function() {
// Get the iFrame's document object
var iFrameDoc = myIframe.contentDocument;
if (iFrameDoc) {
// Add event listener for when the iframe's document is clicked
iFrameDoc.addEventListener('click', function() {
// Set the active state on the parent window
document.body.classList.add('active');
// Remove the active state after a short delay (to allow the user to see the active state)
setTimeout(function() {
document.body.classList.remove('active');
}, 200);
});
}
});
}
此代码添加了一个事件监听器,当 iframe 加载时启动。通过监听 click 事件,它将在主窗口中添加一个名为“active”的类来模拟 :active 伪类的行为。这使您可以使用 CSS 来更改子域中 iframe 的样式,就像在同一域中一样。