如何建立动态访客计数器

How to build Dynamic Visitor Counter

大家好,我喜欢在我的 WooCommerce 商店 (WordPress) 上使用伪造的动态访客计数器,我想在购买按钮下方添加这样的计数器:

在这个例子中,它有时减少有时增加完全动态。

我希望这个数字是 运行 b/w 200-5000 所以它不会增加超过 5000 也不会减少到 200 以下也不会立即从 500-200 下降它应该是缓慢而稳定的增加和减少。

只是一个想法:

<!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>

使用一些 JS,您可以实现它。使用 Math.random() 方法并使用 setInterval().

使计数每 n 秒更改一次

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>