我遇到一种情况,我想使用window.location.href = id
跳转到特定的内容,但是它适用于普通页面,但是不能在iframe
内使用
问题:如何在iframe
内跳转到该特定内容
这是jsfiddle:http://jsfiddle.net/TH48e/3289/
下面是完整代码:
var $iframe = $('#iframe');
$iframe.ready(function() {
$iframe.contents().find("body").append(
`<div id="content1"> CONTENT 1 Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quisquam laborum, dolore iusto expedita accusamus, minima temporibus cum, doloremque ullam non incidunt quam earum ducimus iure sapiente dicta. Laborum, consequuntur, rerum! <hr/></div>
<br>
<div id="content2"> CONTENT 2 Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quisquam laborum, dolore iusto expedita accusamus, minima temporibus cum, doloremque ullam non incidunt quam earum ducimus iure sapiente dicta. Laborum, consequuntur, rerum! <hr/></div>
<br>
<div id="content3"> CONTENT 3 Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quisquam laborum, dolore iusto expedita accusamus, minima temporibus cum, doloremque ullam non incidunt quam earum ducimus iure sapiente dicta. Laborum, consequuntur, rerum! <hr/></div>
<br>
<div id="content4"> CONTENT 4 Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quisquam laborum, dolore iusto expedita accusamus, minima temporibus cum, doloremque ullam non incidunt quam earum ducimus iure sapiente dicta. Laborum, consequuntur, rerum! <hr/></div>
<br>` );
// above iframe creation code
//actual code
var index = 0;
$('#loopcontent').on('click',function(){
index++;
if(index > 4) index = 0;
console.log('content id','#content'+index);
window.location.href = '#content'+index;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<iframe id="iframe"></iframe>
<button id="loopcontent">
go to content
</button>
请提前帮助我!!!
答案 0 :(得分:1)
您正在您的窗口中设置位置。
window.location.href = '#content'+index;
IFrame具有its own window,您需要在此处设置位置:
document.getElementById('iframe').contentWindow.location.hash = 'content'+index;
此外,如果IFrame src来自另一个"Origin",则您将无法访问其内容,这将无法正常工作。
答案 1 :(得分:1)
您可以使用javascript将所需的div滚动到视图中,
$('#loopcontent').on('click',function(){
index++;
if(index > 4) index = 1;
$iframe_window = $iframe.contents();
var $div = $iframe_window.find('#content'+index);
$iframe_window.find('body').scrollTop($div.offset().top);
});
请参见jsFiddle here