簡體   English   中英

如何阻止多個書簽出現?

[英]How do I stop multiple bookmarklets from appearing?

我正在制作一個小書簽,它會彈出一個包含各種內容的 div……當您單擊鏈接兩次打開小書簽時,會彈出兩個小書簽。 我該如何防止這種情況發生?

索引.html:

<html>
<head>
<title>Bookmarklet Home Page</title>
<link rel="shortcut icon" href="favicon.ico" />
</head>
<body>
<a href="javascript:(function(){code=document.createElement('SCRIPT');code.type='text/javascript';code.src='code.js';document.getElementsByTagName('head')[0].appendChild(code)})();">click here</a>
</body>
</html>

代碼.js:

function toggle_bookmarklet() {
    bookmarklet = document.getElementById("bookmarklet");
    if (bookmarklet.style.display == "none") {
        bookmarklet.style.display = "";
    }
    else {
        bookmarklet.style.display = "none";
    }
}
div = document.createElement("div");
div.id = "bookmarklet";
div.style.margin = "auto";
div.style.position = "fixed";
content = "";
content += "<a href='javascript:void(0);'><div id='xbutton' onClick='javascript:toggle_bookmarklet();'>x</div></a>";
div.innerHTML = content;
document.body.appendChild(div);

只需在創建之前檢查div是否存在。

var div = document.getElementById("bookmarklet");
if (!div)
{
    div = document.createElement("div");
    div.id = "bookmarklet";
    div.style.margin = "auto";
    div.style.position = "fixed";
}

此外,由於您已經擁有對div的全局引用,因此您無需在toggle_bookmarklet中通過 id 搜索它。 你可以參考div 不過,我會嘗試選擇一個更獨特的名稱,以避免遇到命名沖突。

編輯:就此而言,如果您要使用全局變量,則可以進一步簡化。 甚至不用給它一個 id,只需使用全局引用:

function toggle_bookmarklet() {
    bookmarkletEl.style.display = bookmarkletEl.style.display == "none" ? "" : "none";
}
if (!window.bookmarkletEl) {
    var bookmarkletEl = ddocument.createElement("div");
    bookmarkletEl.style.margin = "auto";
    bookmarkletEl.style.position = "fixed";
}

暫無
暫無

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

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