我被分配了一個任務來創建一個腳本,當鼠標光標移到當前打開的瀏覽器選項卡上時,該腳本將生成一個彈出窗口。是否有可能檢測鼠標何時位於瀏覽器選項卡上?
像這樣的演示:http://demo.exitmonitor.com/但這裏彈出窗口總是出現在鼠標離開網頁的頂部時。
當鼠標懸停在當前活動瀏覽器選項卡上時,我需要生成此窗口。
這是可能做到這一點與JavaScript?
我被分配了一個任務來創建一個腳本,當鼠標光標移到當前打開的瀏覽器選項卡上時,該腳本將生成一個彈出窗口。是否有可能檢測鼠標何時位於瀏覽器選項卡上?
像這樣的演示:http://demo.exitmonitor.com/但這裏彈出窗口總是出現在鼠標離開網頁的頂部時。
當鼠標懸停在當前活動瀏覽器選項卡上時,我需要生成此窗口。
這是可能做到這一點與JavaScript?
使用MouseEvent.clientX
和MouseEvent.clientY
跟蹤鼠標的位置上的文件,然後把彈出的還有使用absolute
定位:
//The popup:
var span = document.createElement("span");
span.style.position = "absolute";
span.textContent = "I'm a popup!";
//When the page loads, the popup will be in the top-left corner
//because we can't know where the mouse is on the page load.
document.body.insertBefore(span, document.body.firstChild);
//The event:
document.addEventListener("mousemove", function(e) {
//Position the span according to its dimensions and where the mouse is.
span.style.marginLeft = e.clientX-span.clientWidth/2+"px";
span.style.marginTop = e.clientY-span.clientHeight/2+"px";
});
我希望它在鼠標在瀏覽器標籤上/內部/在瀏覽器標籤上彈出 –
好的,我修復了我的代碼以適應這種情況。這樣做實際上比跟蹤鼠標離開瀏覽器更容易,因爲您不需要跟蹤它留在哪邊。 –
我想通過「標籤」你的意思是以紅色突出顯示的區域:
在所有現代瀏覽器中,除明確提供給它的API外,網站無法訪問window
以外的任何內容。
因此,您甚至無法使用JavaScript訪問標籤欄。
是否有任何方法可以訪問標籤欄取決於瀏覽器,但它(肯定會)需要瀏覽器插件。
例如,在Chrome中,這是not at all possible back in 2010,它看起來沒有什麼變化。
然而在Firefox中,插件實際上可以做到這一點。
假設你知道如何連接一個腳本來browser.xul,我要離開了install.rdf
,chrome.manifest
和overlay.xul
,所以,這裏僅是相應的JavaScript:
(function()
{
// Wait for the browser to settle
top.addEventListener('load', function load(event)
{
// It only needs to do that once
top.removeEventListener('load', load);
// Get notified about every page that loads
top.gBrowser.addEventListener('DOMContentLoaded', function(event)
{
// Get the current tab
var tab = top.gBrowser.mCurrentTab;
// Check if we already annoyified it
if(tab.annoyingOrange === undefined)
{
// If not, let's do that!
tab.annoyingOrange = 'Plumpkin';
// Add a mouseover event to it
top.gBrowser.mCurrentTab.addEventListener('mouseover', function(ev)
{
// Since we do that to all tabs, we need to check here if we're still the selected tab
if(ev.target == top.gBrowser.mCurrentTab)
{
// And now we can get onto everybody's nerves!
alert('Hey apple!!!');
}
});
}
});
});
})();
測試在Windows上的Firefox 37.0.1。
[Download .xpi](普羅蒂普:解壓縮源)
但是如果你的瀏覽器不支持它,你的運氣並沒有什麼可以做!
無論如何,這是一個非常糟糕的事情做,它苦惱的人沒有結束!
這應該是從來沒有,永遠不會在生產或甚至測試版環境中完成!
我相信你需要鼠標離開事件:
<script>
function addEvent(obj, evt, fn) {
if (obj.addEventListener) {
obj.addEventListener(evt, fn, false);
}
else if (obj.attachEvent) {
obj.attachEvent("on" + evt, fn);
}
}
addEvent(window, "load", function (e) {
addEvent(document, "mouseleave", function (e) {
e = e ? e : window.event;
var from = e.relatedTarget || e.toElement;
if (!from || from.nodeName == "HTML") {
//.... do_this
}
});
});
</script>
不可能檢測和惱人 – epascarello
這是不可能的。你所能做的只是在'document'上附加一個'mouseleave'事件,這樣你就知道鼠標何時離開文檔,但不知道它到了什麼地方。 –
在一些使用JS編寫插件的瀏覽器中可能會出現這種情況。然而,這樣的事情會讓人絕對憤怒。 – Siguza