[英]Javascript - Ternary Operator - Comparing same function twice?
I have 3 variables top, mid, bot
that I want to be logged depending on which part the div
pops up (if topmost part of div
, then top
would be logged) 我有3个变量
top, mid, bot
分别是div
弹出的top, mid, bot
,这取决于div
弹出的部分(如果div
最高部分,则将记录top
)
All you need to know is as the user scrolls down from the top of page, there are certain divs
that we want to target. 您需要知道的是,当用户从页面顶部向下滚动时,我们要定位某些
divs
。 The 3 variables represent what needs to be logged whenever we hit a certain part of the div. 这三个变量表示每当我们到达div的某个部分时需要记录的内容。
How would rewrite the console.log
ternary operator to make sense, right now, the mid is not being run at all. 现在如何重写
console.log
三元运算符console.log
意义,中间根本没有运行。
EDIT 编辑
trgt1 and trgt2
are 2 divs with the class ( .column
). trgt1 and trgt2
是具有类( .column
)的2个div。 trgt1
is the very first div that shows up, trgt2
should pop up as we scroll through halfway through the div. trgt1
是显示的第一个div,当我们滚动浏览div的一半时, trgt2
应该弹出。
CODE 码
function onScroll(event){
let top = "Column with id:`id-10` started to become visible on the page."
let mid = "Column with id:`id-50` is now more than 50% visible on the page."
let bot = "Column with id:`id-40` is now fully visible on the page."
targets.forEach(
function(trgt,index){
let isVisible = isScrolledIntoView(trgt);
if (visibleStates[index] != isVisible)
console.log(`Element index ${index} is now ${isVisible === trgt1 ? top : (isVisible === trgt2 ? mid : bot)}`);
visibleStates[index] = isVisible;
}
);
}
You could work with a script that runs on scrolling the page. 您可以使用在滚动页面时运行的脚本。 So add an eventlistener to the page.. Then you can debounce the scrolling, so control the amount of noise you allow on the window.. The function I have included is a working debounce function, just play with the wait in milliseconds.
因此,在页面上添加一个事件侦听器。然后,您可以消除滚动的抖动,从而控制窗口上允许的噪声量。我包含的功能是一个有效的消除抖动功能,只需等待几毫秒即可播放。 And then use your debounce function on the checkSlide() function where you put your running code in.
然后在将运行代码放入其中的checkSlide()函数上使用反跳函数。
I know this is not a direct answer, it is another way of approaching the problem. 我知道这不是直接的答案,而是解决问题的另一种方式。 This could work.
这可能有效。 If you want to do it your way, go for it..
如果您想按照自己的方式做,那就去吧。
Good luck! 祝好运!
window.addEventListener('scroll', debounce(checkSlide));
function checkSlide(){}
function debounce(func, wait=20, immediate = true){
var timeout;
//debounce is a higher order function and will return another function
return function run_code() {
var context = this;
//arguments is local variable of a function, refers to all arguments
var args = arguments;
//variable later is a function
var later = function(){
timeout = null;
//if it is not time zero, apply checkSlide function
if(!immediate) func.apply(context, args);
};
var Callnow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if(Callnow) func.apply(context, args);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.