jquery $(window).blur事件影响Iframe

mfuanj7w  于 2023-08-04  发布在  jQuery
关注(0)|答案(4)|浏览(139)

我想检测用户何时离开我的页面(例如打开一个新标签),这样我就可以停止倒计时。我使用了:

  1. $(window).blur(function() {
  2. //stop countdown
  3. });

字符串
但是我的页面中有一个Iframe,当用户单击它时,倒计时也会停止,但我不希望当有人单击Iframe时执行上述事件。
你知道吗?
更新,我正在尝试更多,基于这个答案Click-event on iframe?

  1. iframeDoc = $('iframe').contents().get(0);
  2. $(iframeDoc).click(function(){
  3. //maybe remove blur event?
  4. });


更新:Tim B解决方案有效:

  1. $(window).blur(function () {
  2. // check focus
  3. if ($('iframe').is(':focus')) {
  4. // dont stop countdown
  5. }
  6. else {
  7. // stop countdown
  8. }
  9. });


现在我必须在每次调用模糊事件时从Iframe中移除焦点,否则如果用户在聚焦Iframe后更改选项卡,倒计时将不会停止。我试着这样使用上面的条件:

  1. if ($('iframe').is(':focus')) {
  2. // dont stop countdown
  3. $("iframe").blur()
  4. $(window).focus();
  5. }


但这并不奏效。你知道吗?

f8rj6qna

f8rj6qna1#

一个解决方案是检查iframe是否具有焦点,然后不停止计时器。例如,在

  1. $(window).blur(function () {
  2. // check focus
  3. if ($('iframe').is(':focus')) {
  4. // dont stop countdown
  5. }
  6. else {
  7. // stop countdown
  8. }
  9. });

字符串
现在这将工作,但是如果您的iframe在用户更改标签时具有焦点,倒计时将不会停止。因此,在这种情况下,你需要考虑一个优雅的解决方案,将焦点从iframe prior转移开。例如,如果用户在iframe内单击,则会将焦点内在地移回父窗口。

编辑-更新了答案以包含额外的iframe功能

好吧,我一直在玩这个。现在我不知道你的iframe中有什么内容,但你可以添加一些代码,基本上当点击父窗口时,它会将焦点发送回父窗口中的对象。例如,在
在iFrame中

  1. <script>
  2. $(function () {
  3. $(document).click(function () {
  4. // call parent function to set focus
  5. parent.setFocus();
  6. });
  7. });
  8. </script>


在您的主页中

  1. <script>
  2. function setFocus() {
  3. // focus on an element on your page.
  4. $('an-element-on-your-page').focus();
  5. }
  6. $(function () {
  7. $(window).focus(function (e) {
  8. // bind the blur event
  9. setBindingEvent();
  10. });
  11. var setBindingEvent = function () {
  12. // unbind
  13. $(window).unbind('blur');
  14. $(window).blur(function () {
  15. // check focus
  16. if ($('iframe').is(':focus')) {
  17. // unbind the blur event
  18. $(window).unbind('blur');
  19. }
  20. else {
  21. // stop countdown
  22. }
  23. });
  24. };
  25. setBindingEvent();
  26. });
  27. </script>


这将允许您单击iframe,将焦点设置回主页,然后停止倒计时。

展开查看全部
ia2d9nvy

ia2d9nvy2#

由于iframe的隔离性,在它内部单击对于父级来说会被视为模糊。如果iframe的内容可以通过 AJAX 引入,那将是一个更好的选择。

dwthyt8l

dwthyt8l3#

我也有同样的问题。在我的情况下,我没有访问iframe页面和它的加载CMS,我不能改变所有的iframe。我的计时器用setInterval()计数,在间隔内,我检查Iframe。

  1. const focus = function() {
  2. // timer start
  3. isBlured = 0;
  4. };
  5. const blur = function() {
  6. // timer stop
  7. isBlured = 1;
  8. }
  9. window.addEventListener('focus', focus);
  10. window.addEventListener('blur', blur);
  11. function intervalFunction() {
  12. var activeELM = document.activeElement.tagName;
  13. if (isBlured == 0 || activeELM == "IFRAME"){
  14. // dont stop countdown
  15. var stopIframe = $('iframe').blur();
  16. }
  17. }

字符串

展开查看全部
c8ib6hqw

c8ib6hqw4#

如果你不需要与iframe交互,你现在可以用CSS阻止它获得焦点。

  1. iframe {
  2. pointer-events: none;
  3. }

字符串

相关问题