css animations created by javascript [closed]

2020-03-08 05:54发布

I am trying to create a div with a css3 animated timer in it when a button is pressed. heres the code: http://jsfiddle.net/arcco96/y5nov6rz/1/. For some reason it will not create the div. I think the code should be functional but I am not sure whether or not one can create a div with a css animation after the page load.

My fiddle is based on this one: http://jsfiddle.net/zbGCq/118/.

I am creating the div with:

$("#btn1").click(function(){
jQuery('<div/>', {
    class: 'timer',
}).appendTo('#center');
jQuery('<div/>', {
    class: 'mask',
}).appendTo('#center');
});

Any thoughts?

thanks

p.s. on a slightly unrelated note will I be able to overlay content on the #timer or will that be impossible?

2条回答
小情绪 Triste *
2楼-- · 2020-03-08 06:24

You were trying to jquery objects before they existed.

the css is still broken in my firefox, but the javascript is working,

It does something animated in chromium, I don't know if that's the effect you want or not.

http://jsfiddle.net/Lbuseo9j/

var cv = $('.container').width();
$('.head').css({
    'height': (cv / 3) + 'px'
});

$("#btn1").click(function () {
    jQuery('<div/>', {
        class: 'timer',
    }).appendTo('#center');

    var cw = $('.timer').width();
    $('.timer').css({
        'height': cw + 'px'
    });

    jQuery('<div/>', {
        class: 'mask',
    }).appendTo('#center');
});
查看更多
做自己的国王
3楼-- · 2020-03-08 06:25

I would do this by animating svg's path element through JavaScript.

You can set the width and height of the timer by changing the width variable. You can also change the animation speed through the t variable.

Demo on CodePen

var timer = document.getElementById('timer');
var svg = document.getElementById('svg');
var width = 150;
svg.setAttribute('width', width);
svg.setAttribute('height', width);
var t = 5;
var theta = 0;
var radius = svg.getAttribute('width') / 2;
timer.setAttribute('transform', 'translate(' + radius + ',' + radius + ')');

(function animate() {
  theta += 0.5;
  theta %= 360;
  var x = Math.sin(theta * Math.PI / 180) * radius;
  var y = Math.cos(theta * Math.PI / 180) * -radius;
  var d = 'M0,0 v' + -radius + 'A' + radius + ',' + radius + ' 1 ' + ((theta > 180) ? 1 : 0) + ',1 ' + x + ',' + y + 'z';
  timer.setAttribute('d', d);
  setTimeout(animate, t)
})();
body {
  background: #333333;
  text-align: center;
}
<svg id="svg">
  <path id="timer" fill="lightseagreen" />
</svg>

查看更多
登录 后发表回答