如何用Alpine.js实现每60秒显示元素1秒?
问题描述
想用Alpine.js的x-show指令让某个元素仅显示1秒,且每60秒重复一次。已写了一个JavaScript计时器(可能冗余),能通过x-text显示倒计时秒数并重置,但不知道x-show该设置什么判断条件,才能让指定元素在设定时间显示。
HTML/Alpine代码:
<p x-text="time().seconds"></p> <div x-show="time().seconds.value === 48"> hello </div>
JavaScript计时器代码:
function timer(expiry) { return { expiry: expiry, remaining:null, init() { this.setRemaining() setInterval(() => { this.setRemaining(); }, 1000); }, setRemaining() { const diff = this.expiry - new Date().getTime(); this.remaining = parseInt(diff / 1000); }, days() { return { value:this.remaining / 86400, remaining:this.remaining % 86400 }; }, hours() { return { value:this.days().remaining / 3600, remaining:this.days().remaining % 3600 }; }, minutes() { return { value:this.hours().remaining / 60, remaining:this.hours().remaining % 60 }; }, seconds() { return { value:this.minutes().remaining, }; }, format(value) { return ("0" + parseInt(value)).slice(-2) }, time(){ return { days:this.format(this.days().value), hours:this.format(this.hours().value), minutes:this.format(this.minutes().value), seconds:this.format(this.seconds().value), } }, } }
解决方案
方案1:简化逻辑(推荐)
不需要复杂的倒计时expiry,直接基于当前时间的秒数判断即可实现需求:
<div x-data="{ currentSecond: 0 }" x-init="setInterval(() => currentSecond = new Date().getSeconds(), 1000)"> <p x-text="currentSecond"></p> <!-- 示例:元素在每分0秒时显示1秒,每60秒重复一次 --> <div x-show="currentSecond === 0">hello</div> </div>
这段代码会每秒更新当前秒数,当秒数为0时,元素显示1秒,下一秒自动隐藏,完全匹配“每60秒显示1秒”的要求。
方案2:基于现有计时器修改
如果要沿用已有的timer函数,需要补充两个关键逻辑:
- 倒计时结束后重置,实现循环;
- 添加判断方法供
x-show调用。
修改后的计时器代码:
function timer(expiry) { return { expiry: expiry, remaining: null, init() { this.setRemaining() setInterval(() => { this.setRemaining(); }, 1000); }, setRemaining() { const diff = this.expiry - new Date().getTime(); this.remaining = parseInt(diff / 1000); // 倒计时结束后重置为60秒,实现循环 if (this.remaining < 0) { this.expiry = new Date().getTime() + 60 * 1000; this.setRemaining(); } }, days() { return { value: this.remaining / 86400, remaining: this.remaining % 86400 }; }, hours() { return { value: this.days().remaining / 3600, remaining: this.days().remaining % 3600 }; }, minutes() { return { value: this.hours().remaining / 60, remaining: this.hours().remaining % 60 }; }, seconds() { return { value: this.minutes().remaining, }; }, format(value) { return ("0" + parseInt(value)).slice(-2) }, time() { return { days: this.format(this.days().value), hours: this.format(this.hours().value), minutes: this.format(this.minutes().value), seconds: this.format(this.seconds().value), } }, // 添加判断方法,指定剩余秒数为48时显示 shouldShowElement() { return this.seconds().value === 48; } } }
对应的HTML修改:
<div x-data="timer(new Date().getTime() + 60 * 1000)"> <p x-text="time().seconds"></p> <div x-show="shouldShowElement()">hello</div> </div>
这样每当倒计时剩余48秒时,元素会显示1秒,倒计时结束后自动重置为60秒,循环触发显示。
内容的提问来源于stack exchange,提问作者Dan Sinker
相关产品推荐
相关产品推荐

