使用jQuery setInterval减小元素的宽度,但仅从一侧(左侧或右侧)

问题描述 投票:0回答:2

这是我的代码,用于减小选定元素的宽度(class =“ life_bar”),但是如我所附的图片所示,我希望它从左或右减小宽度(以左为例),但是总是从两边走,我该怎么办?enter image description hereenter image description here这是jQuery代码

$(function () {
    var timmer;
    gocount();
    function gocount(){
        timmer = setInterval(function () {
         var life_bar_width = $(".life_bar").width();
            life_bar_width -= 100;
            $(".life_bar").css( {width: life_bar_width,
                left: '-50px'})
        },1000);
    }
});

这里是CSS代码

.life_bar{
    width: 500px;
    height: 10px;
    background: crimson;
    margin: 100px auto;
}

这里是html代码

<body>
<div class="life_bar"></div>
</body>
javascript jquery dom
2个回答
0
投票

$(function () {
var timmer;
gocount();
function gocount(){
    timmer = setInterval(function () {
     var life_bar_width = $(".life_bar").width();
        life_bar_width -= 100;
        $(".life_bar").css( {width: life_bar_width,
            left: '-50px'})
    },1000);
}
});
.life_bar{
width: 500px;
height: 10px;
background: crimson;
margin: 100px auto;
float: left;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="life_bar"></div>

0
投票

在每个间隔刻度上对X使用负的平移:

$(function () {
  var timmer;
  gocount();
  let counter = 1
  function gocount(){
    timmer = setInterval(function () {
     var life_bar_width = $(".life_bar").width();
      life_bar_width -= 100;
      $(".life_bar").css({
        width: life_bar_width,
        left: '-50px',
        transform: `translate(${-50*counter}px)`
      })
      counter++
    },1000);
  }
});
.life_bar{
    width: 500px;
    height: 10px;
    background: crimson;
    margin: 100px auto;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="life_bar"></div>
© www.soinside.com 2019 - 2024. All rights reserved.