简体   繁体   English

jQuery如何使条件不只运行一次。

[英]JQuery How to make condition not to run only once.

I have a little problem with conditions and its triggering. 我对条件及其触发有一点问题。 I have 2 object in my HTML (div and img), that I am trying to constantly align by JS. 我的HTML中有2个对象(div和img),我试图通过JS不断对齐。 By constantly I mean so that when window size changes, they realign (since one is aligned to the center - and no :), I can't center-align the second one as well, because I also need to match the size, which definitely requires JS). 我经常说的是,当窗口大小改变时,它们会重新对齐(因为一个窗口与中心对齐-否:),我也无法对第二个窗口进行居中对齐,因为我还需要匹配该大小,绝对需要JS)。

I made a little function that aligns them and sets proper dimensions to it and I am triggering the function on every window.onresize event (as well as on document ready). 我做了一个对齐它们并为其设置适当尺寸的小函数,并在每个window.onresize事件(以及准备就绪的文档)上触发该函数。 But I found out, that it does not trigger on zoom action and besides that it would be more suitable for me not to be dependent on window.onresize. 但是我发现,它不会触发缩放动作,此外,它不依赖window.onresize更适合我。

So I thought there would be a posibility to write a condition like 所以我认为写这样的条件是可能的

if (div.width() != img.widht()) { // do something to match it again }

But it turned out to only run this condition on the ready event (resp. load event, since I have a picture). 但是事实证明,仅在ready事件(resp。load事件,因为我有图片)上运行此条件。 So my question is, if there is any way, so that the condition would be checking its state just continuosly? 所以我的问题是,是否有办法使条件能够连续地检查其状态? I know, I can probably set Interval to take care of that, but a) I guess that like 99% of all executions would be pointless and b) unless I set it to like very quick repetition, it would not even fix the div's and img's mismatch problem immediately. 我知道,我可能可以设置Interval来解决此问题,但是a)我想所有执行中的99%都是毫无意义的,b)除非我将其设置为非常快速的重复,否则它甚至无法修复div的问题,并且img的不匹配问题立即出现。

Thank you very much. 非常感谢你。

You can certainly define you own custom event and execute the aligning code when it occurs, but you still need a way to fire the event at appropriate time. 您当然可以定义自己的自定义事件,并在事件发生时执行对齐代码,但是您仍然需要一种在适当时间触发事件的方法。 That can only happen during the ordinary execution flow of the program (not an option here) or in the handler for one of the existing events: if none of those events is consistently fired when the trigger condition occurs, then you're only left with timers. 这只能在程序的常规执行流程中(此处不是选项)或在现有事件之一的处理程序中发生:如果在触发条件发生时没有一致触发这些事件,那么您将只剩下计时器。 I'd be happy to be wrong on this, tho'. 我很乐意在这个问题上做错事情。

Consider requestAnimationFrame as an alternative to setInterval . 考虑使用requestAnimationFrame作为setInterval的替代方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM