簡體   English   中英

用div內容打開一個新頁面

[英]Open a new page with div contents

我在具有特定ID的HTML頁面中有一些隱藏的div:

<div id='log1' style='visibility: hidden;display: none;'>content</div>
<div id='log2' style='visibility: hidden;display: none;'>content</div>

然后是一些鏈接:

<a href='?' target='_blank'>Log 1</a>
<a href='?' target='_blank'>Log 2</a>

我希望瀏覽器使用相應的div的內容打開一個新的頁面/選項卡(甚至彈出窗口,但是如果用戶具有彈出窗口阻止程序,則可能會很不好)。

我知道我可以做一些Javascript來創建一個浮動div並在同一頁面中顯示數據,但是我想避免這種情況。 而且,如果沒有JS(我懷疑)的話,是否有一種方法可以做得更好。

不使用JavaScript,就無法基於HTML中的隱藏div彈出窗口。 有一個CSS技巧,如果您將div遠離頁面並為其提供ID,然后將其鏈接為錨點,則瀏覽器會將其滾動到視圖中。

在JavaScript方面,這非常簡單。 首先,向他們添加一個data-log屬性,以告訴我們應該顯示什么日志,然后:

var links = document.querySelectorAll("...some selectors for your links...");
Array.prototype.forEach.call(links, function(link) {
    link.onclick = function() {
        var log = document.getElementById(this.getAttribute("data-log"));
        var wnd = window.open("", "_blank");
        wnd.document.write(
            "<!doctype html>" +
            "<html><head>" +
            "<meta charset='appropriate charset here'>" +
            "<title>Title here</title>" +
            "</head><body>" +
            "<div>" + log.innerHTML + "</div>" +
            "</body></html>"
        );
        wnd.document.close();
        return false; // Prevents the default action of following the link
    };
});

注意window.open必須點擊處理程序中完成; 如果彈出窗口是直接響應用戶操作,則大多數彈出窗口阻止程序將允許彈出窗口。

window.open返回對該窗口的引用,然后我們可以寫入其文檔。


(我通常不使用onclick處理程序,但是您沒有提到使用任何庫,並且那里仍然有很多IE8。使用onclick可以讓我們使用return false來防止出現默認值; 這篇小文章中的詳細信息關於我貧乏的內容博客。)

var newWindow = window.open("about:blank", "", "_blank");
newWindow.document.write(html);

在這種情況下,您應該在回叫中使用javascript進行此操作,它可能是頁面加載或單擊按鈕或其他原因

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM