我试图在 iframe 中隐藏一个元素(同源),但没有成功。在这里尝试: https://www.w3schools.com/tags/tryit.asp?filename=tryhtml_script
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function()
{
$("#iframeID").css({"color": "red", "border": "2px solid red"});
$('#iframeID').on('load', function()
{
console.log($('#iframeID').contents().find('#mySidenav'));
$('#iframeID').contents().find('#mySidenav').hide();
});
});
</script>
</head>
<body>
<iframe id="iframeID" height="800px" width="800px" src="https://www.w3schools.com/" ></iframe>
</body>
</html>
侧边栏就是不隐藏,怎么了?这是我试图隐藏的那个网站上的元素:
<nav class="w3-sidebar w3-collapse w3-white w3-card-2" id="mySidenav">
最佳答案
我怀疑这是因为页面上有一些 HTML。当我使用 remove() 它工作正常。很可能在 CSS 中的某处有 display: block !important
。
html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function()
{
$("#iframeID").css({"color": "red", "border": "2px solid red"});
$('#iframeID').on('load', function()
{
console.log($('#iframeID').contents().find('#mySidenav').remove());
});
});
</script>
</head>
<body>
<iframe id="iframeID" height="800px" width="800px" src="https://www.w3schools.com/" ></iframe>
</body>
</html>
关于javascript - 为什么这个最简单的 jQuery 在 iframe 代码中隐藏元素即使在同源上也不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43821703/