Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
502 views
in Technique[技术] by (71.8m points)

javascript - 如何判断浏览器/标签是否有效[重复](How to tell if browser/tab is active [duplicate])

Possible Duplicate:(可能重复:)

I have a function that is called every second that I only want to run if the current page is in the foreground, ie the user hasn't minimized the browser or switched to another tab.(我有一个每秒调用的函数,如果当前页面在前台,我只想运行,即用户没有最小化浏览器或切换到另一个选项卡。)

It serves no purpose if the user isn't looking at it and is potentially CPU-intensive, so I don't want to just waste cycles in the background.(如果用户没有看到它并且可能是CPU密集型的话,它没有用处,所以我不想在后台浪费周期。) Does anyone know how to tell this in JavaScript?(有谁知道如何在JavaScript中讲述这个?) Note: I use jQuery, so if your answer uses that, that's fine :).(注意:我使用jQuery,所以如果你的答案使用它,那很好:)。)   ask by ckknight translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You would use the focus and blur events of the window:(您将使用窗口的focusblur事件:)

var interval_id; $(window).focus(function() { if (!interval_id) interval_id = setInterval(hard_work, 1000); }); $(window).blur(function() { clearInterval(interval_id); interval_id = 0; }); To Answer the Commented Issue of "Double Fire" and stay within jQuery ease of use:(回答“双火”的评论问题并保持jQuery的易用性:) $(window).on("blur focus", function(e) { var prevType = $(this).data("prevType"); if (prevType != e.type) { // reduce double fire issues switch (e.type) { case "blur": // do work break; case "focus": // do work break; } } $(this).data("prevType", e.type); }) Click to view Example Code Showing it working (JSFiddle)(单击以查看示例代码显示它正常工作(JSFiddle))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...