大家好,我喜欢在我的 WooCommerce 商店(WordPress)上使用假的动态访客计数器,我喜欢在购买按钮下方添加这样的计数器:
在这个例子中,它有时会减少,有时会完全动态地增加。
我希望数字以 200-5000 的速度运行,因此它不会增加超过 5000,也不会低于 200,也不会立即从 500-200 下降,它应该缓慢而稳定地增加和减少。
使用一些 JS 你可以把它拉下来。使用该Math.random()
方法并使用 . 使计数每 n 秒更改一次setInterval()
。
function random(min,max)
{
return Math.floor(Math.random()*(max-min+1)+min);
}
var initial = random(500, 2000);
var count = initial;
setInterval(function() {
var variation = random(-5,5);
count += variation
console.log('You currently have ' + count + ' visitors')
}, 2000)
您可以更改变化(这里它在 -5 和 5 之间)以及间隔(这里是每 2 秒)。
慎用JS的话,可以看源码中的代码……玩得开心。
编辑
这是嵌入在 HTML 中的代码,您可以更改interval
(两次更新之间的毫秒数)和variation
(计数可以变化多少±)。您可能希望将 更改interval
为更高的值。
奖励:使用 CSS 进行一些样式设置
#counter-area {
padding: 2px;
background-color: rgba(205, 204, 204, 0.19);
border-radius: 2px;
width: 300px;
height: 30px;
line-height: 30px;
text-align: center;
}
#counter {
color: white;
background-color: red;
padding: 4px 6px;
border-radius: 5px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<div id="counter-area">Real time <span id="counter"></span> visitors right now</div>
</body>
<script>
function r(t,r){return Math.floor(Math.random()*(r-t+1)+t)}var interval=2e3,variation=5,c=r(500,2e3);$("#counter").text(c),setInterval(function(){var t=r(-variation,variation);c+=t,$("#counter").text(c)},interval);
</script>
</html>
只是一个想法:
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"> </script>
<script type="text/javascript">
$(document).ready(function() {
function setCounterValue() {
var random = Math.floor(Math.random() * (5000 - 1000 + 1)) + 1000;
$("div#counter").html("visitor "+random);
setTimeout(function(){ setCounterValue(); }, 3000);
}
setCounterValue();
setTimeout(function(){ setCounterValue(); }, 3000);
});
</script>
</head>
<body>
<div id="counter"></div>
</body>
</html>