how to open different URLs in iframes using JavaScript and HTML buttons

与世无争的帅哥 提交于 2020-05-30 11:27:42

问题


So I want to make a small website with a menu that has four HTML buttons. Instead of the buttons opening a completely new website I just want an iframe tag to change the URL it's displaying according to the buttons that are pressed.

Please keep it simple, I am a beginner in HTML, JS and CSS. Thanks!


回答1:


You just need to get the iframe element with Javascript and change the src attribute The question has already been answered here : https://stackoverflow.com/a/6001043/7988438

var frame = document.getElementById("frame");

var btn1 = document.getElementById("btn1");
var btn2 = document.getElementById("btn2");
var btn3 = document.getElementById("btn3");

btn1.addEventListener("click",link1)
btn2.addEventListener("click",link2)
btn3.addEventListener("click",link3)

function link1(){
  frame.src="https://pixabay.com/photo-2845763/"
}
function link2(){
  frame.src="https://pixabay.com/photo-3126513/"
}
function link3(){
  frame.src="https://pixabay.com/photo-3114729/"
}
<button id="btn1" >link1</button>
<button id="btn2" >link2</button>
<button id="btn3" >link3</button>
<iframe id="frame" src="https://pixabay.com/photo-2845763/"></iframe>

EDITED to take comment into consideration




回答2:


You can use the target attribute of an anchor tag, to tell the link to load in the iframe. I think that's the simplest way.

<iframe src="http://page1.html" id="frame1" name="frame1"></iframe>

<a href="http://page2.html" target="frame1">click here for page 2</a>



回答3:


You can do this by having a function that changes the src attribute of the iframe.

<iframe src="http://cbc.ca/" id="theiframe" width="500" marginwidth="0" height="500" marginheight="0" align="middle" scrolling="auto"></iframe>
<button onclick="loadnewpage('http://bbc.com')">BBC Page</button>
    <button onclick="loadnewpage('http://cbc.ca')">CBC Page</button>

<script>
    function loadnewpage(newsrc){
        var newloc = newsrc;
        document.getElementById('theiframe').setAttribute('src', newloc);
    }
</script>

Check out JS function paramaters and arguments to learn more about how this works



来源:https://stackoverflow.com/questions/48632163/how-to-open-different-urls-in-iframes-using-javascript-and-html-buttons

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!