2017-08-24 124 views
0

我有一個返回true或false的函數。現在我想在函數返回「true」時執行一些代碼。

該功能確定一個元素是否在屏幕上可見。我從here

該元素在頁面加載後1-2秒後顯示。但是,因爲這也與用戶的互聯網連接有關,所以我不想使用setTimout函數。 我嘗試了幾件事,發現它在if/else語句中工作,但不在when/then中。任何想法,這裏出了什麼問題?

我測試了幾件事情,看到代碼

//below if else statement works fine and logs the correct result 
    if($(".myClass").isOnScreen()==true){ 
     console.log("true"); 
    } 
    else{console.log("false");} 

//however i would like to use this one and it doesn't seem to work 
$.when($(".myClass").isOnScreen()==true).then(function(){ 
    console.log($(".myClass").isOnScreen()); 
    setTimeout(function(){ 
     console.log($(".myClass").isOnScreen()); 
    },1000); 
}); 

下面什麼時候/ then語句實際上做: 它儘快功能isOnScreen運行運行,但不會等到回反應是真實的。因此,控制檯日誌始終爲false。 然後我實現了一個timeOut(僅用於測試目的)。 timeOut運行完成後,控制檯日誌始終爲false。

它應該做什麼: 當結果變爲true時,應該運行when /語句。

+1

'isOnScreen'看起來像一個**'sync' **操作,如果在承諾/超時把它包,您將以不一致的行爲結束...... – Hitmands

+0

您鏈接的邏輯被設計爲在「scroll」事件處理程序中使用。它不會返回承諾,也不應該與其中一個使用 –

回答

1

您鏈接的邏輯旨在用於scroll事件處理程序。它不會返回承諾,也不應該與其中一個使用。

爲了解決您的問題,使用這樣的插件:

$.fn.isOnScreen = function() { 
 
    var element = this.get(0); 
 
    var bounds = element.getBoundingClientRect(); 
 
    return bounds.top < window.innerHeight && bounds.bottom > 0; 
 
} 
 
var $output = $('.output'), $foo = $('.foo'); 
 

 
// the important part: 
 
$(window).on('scroll', function() { 
 
    $output.text('visible: ' + $foo.isOnScreen()); 
 
});
.box { 
 
    width: 50px; 
 
    height: 50px; 
 
    margin: 10px; 
 
    background-color: #CCC; 
 
} 
 

 
.foo { 
 
    background-color: #C00; 
 
} 
 

 
.output { 
 
    position: fixed; 
 
    top: 50px; 
 
    right: 50px; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="box"></div> 
 
<div class="box"></div> 
 
<div class="box"></div> 
 
<div class="box"></div> 
 
<div class="box"></div> 
 
<div class="box"></div> 
 
<div class="box"></div> 
 
<div class="box"></div> 
 
<div class="box"></div> 
 
<div class="box foo"></div> 
 
<div class="box"></div> 
 
<div class="box"></div> 
 
<div class="box"></div> 
 
<div class="box"></div> 
 
<div class="box"></div> 
 
<div class="box"></div> 
 
<div class="box"></div> 
 
<div class="box"></div> 
 
<div class="box"></div> 
 
<div class="box"></div> 
 
<div class="box"></div> 
 
<div class="box"></div> 
 
<div class="box"></div> 
 
<div class="box"></div> 
 
<div class="box"></div> 
 
<div class="box"></div> 
 
<div class="box"></div> 
 
<div class="box"></div> 
 
<div class="box"></div> 
 
<div class="box"></div> 
 

 
<div class="output"></div>