gpt4 book ai didi

javascript - 如何使倒计时可与对象重复使用?

转载 作者:行者123 更新时间:2023-12-02 23:12:24 24 4
gpt4 key购买 nike

我有一个在点击事件时运行的倒计时。我需要使这个程序面向对象。我想用构造函数创建一个对象,这样我的倒计时就可以在我想要的每个 div 中运行。如果有人可以向我展示如何使用构造函数创建一个清晰的对象,并在 main.js 文件中调用它,我将能够将我想要的目标 div 的 id 放入参数中。

html

</button>

<div id="target">

</div>

<div id="targetbis">

</div>

js倒计时

var timeout;


function countdownto(target, time, callback) {
var finish = new Date(time);
var s = 1000,
m = s * 60,
h = m * 60,
d = h * 24;

(function timer() {
var now = new Date();
var dist = finish - now;

var days = Math.floor(dist / d),
hours = Math.floor((dist % d) / h),
minutes = Math.floor((dist % h) / m),
seconds = Math.floor((dist % m) / s);

var timestring = minutes + ' minute(s) ' + seconds + ' seconde(s)';
target.innerHTML = timestring

clearTimeout(timeout);

if (dist > 0) {
timeout = setTimeout(timer, 1000);
} else {
callback()
}

})()

}

运行倒计时的js

let runningBtn = document.getElementById("runningbutton")

runningBtn.addEventListener("click", function(e) {


clearTimeout(timeout);
// countdown element
var countdownel = document.getElementById('target');

// 20 min
var time = new Date()
time.setSeconds(time.getSeconds() + 1200)


// countdown function call
countdownto(countdownel, time, function() {
alert('finished');
})


})

我想在 main.js 中添加什么内容

let newCountdown = new Countdown("target");
let newnewCountdown = new Countdown("targetbis");

最佳答案

对象由三部分组成:构造函数、成员方法和成员变量。

// constructor
function Countdown(target,btn){
// member variable
this.target = target
this.btn = btn
this.btn.addEventListener("click", function(e) {
clearTimeout(timeout);
var time = new Date()
time.setSeconds(time.getSeconds() + 1200)
// countdown function call
this.countdownto(this.target, time, function() {
alert('finished');
})
})
}
// member method
Countdown.prototype.countdownto = function(){
...
}

在 es6 语法中,它看起来像:

class Point {
// constructor
constructor(x, y) {
// member variable
this.x = x;
this.y = y;
}

// member method
toString() {
return '(' + this.x + ', ' + this.y + ')';
}
}

关于javascript - 如何使倒计时可与对象重复使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57288768/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com