如何更改值取决于css动画?

时间:2016-06-07 05:42:49

标签: javascript jquery html css animation

我有一个css动画

#sun {
  position: absolute;
  width: 55px;
  height: 55px;
  border: 1px solid red;
  background-color: orange;
  opacity: 0.9;
  border-radius: 100%;
  text-align: center;
  animation: round 3s infinite linear;
}
@keyframes round {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg)
  }
}
<p id="sun">sun</p>
<p id="demo">1</p>

如果demo id的值改变取决于sun rotation。我该怎么办?一些例子,演示初始值是1当时太阳移动25%。演示的值随着2.5的增加而增加。太阳旋转一整圈,demo的值是10.我怎样才能使用 jquery / javascript

请帮帮我。

4 个答案:

答案 0 :(得分:1)

通过使用css我们可以做...

&#13;
&#13;
 <!doctype html>
    <html>
    <head>
    <style>
    #sun {
      position: absolute;
      width: 55px;
      height: 55px;
      border: 1px solid red;
      background-color: orange;
      opacity: 0.9;
      border-radius: 100%;
      text-align: center;
      animation: round 3s infinite linear;
    }
    #demo:after {
      content: "1";
      animation: round1 3s infinite linear;
    }
    @keyframes round {
    	0%   {transform: rotate(0deg);}
        25%  {transform: rotate(90deg);}
        50%  {transform: rotate(180deg);}
        75%  {transform: rotate(270deg);}
        100% {transform: rotate(360deg);}
    }
    @keyframes round1 {
    	0%   {content: "1";}
        25%  {content: "2.5";}
        50%  {content: "5";}
        75%  {content: "7.5";}
        100% {content: "1";}
    }
    </style>
    
    </head>
    
    <body>
    <p id="sun">sun</p>
    <p id="demo"></p>
    </body>
    
    </html>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

你可以这样做。删除CSS动画,并使用jQuery animate()函数。在函数中,您可以为0-360中的变量设置动画,并在step回调函数中设置变换。

&#13;
&#13;
var duration = 3000;
function animateSun() {
  $({degree:0}).stop().animate({degree:360},{
    duration:duration,
    easing : 'linear',
    step:function(val) {
      now = Math.round(val);
      $('#sun').css({
        transform: 'rotate(' + now + 'deg)'
      });
      $('#demo').text(now);
    },
    complete:animateSun
  });
}
animateSun();
&#13;
#sun {
  position: absolute;
  width: 55px;
  height: 55px;
  border: 1px solid red;
  background-color: orange;
  opacity: 0.9;
  border-radius: 100%;
  text-align: center;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<p id="sun">sun</p>
<p id="demo">1</p>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

使用此jQuery代码:

$(document).ready(function(){
    setInterval( function(){
   var rotateVal = getRotationDegrees( $("#sun") );
   var percentRotate = rotateVal / 360 * 10;
   $("#demo").text( percentRotate.toFixed(2) );
  }, 250 )
});//document ready

function getRotationDegrees(obj) {
    var matrix = obj.css("-webkit-transform") ||
    obj.css("-moz-transform")    ||
    obj.css("-ms-transform")     ||
    obj.css("-o-transform")      ||
    obj.css("transform");
    if(matrix !== 'none') {
        var values = matrix.split('(')[1].split(')')[0].split(',');
        var a = values[0];
        var b = values[1];
        var angle = Math.round(Math.atan2(b, a) * (180/Math.PI));
    } else { var angle = 0; }
    return (angle < 0) ? angle + 360 : angle;
}

此代码每250毫秒运行一次函数,检索#sun的旋转角度并相应地更新#demo文本。您可以根据需要修改间隔。

答案 3 :(得分:0)

我使用此代码来绑定动画上的侦听器:

(function() {

var events = {},
    selectors = {},
    animationCount = 0,
    styles = document.createElement('style'),
    keyframes = document.createElement('style'),
    head = document.getElementsByTagName('head')[0],
    startNames = ['animationstart', 'oAnimationStart', 'MSAnimationStart', 'webkitAnimationStart','DOMNodeInserted'],
    startEvent = function(event) {
        event.selector = (events[event.animationName] || {}).selector;
        ((this.selectorListeners || {})[event.animationName] || []).forEach(function(fn) {
            fn.call(this, event);
        }, this);
    },
    prefix = (function() {
        var duration = 'animation-duration: 0.001s;',
            name = 'animation-name: SelectorListener !important;',
            computed = window.getComputedStyle(document.documentElement, ''),
            pre = (Array.prototype.slice.call(computed).join('').match(/moz|webkit|ms/) || (computed.OLink === '' && ['o']))[0];
        return {
            css: '-' + pre + '-',
            properties: '{' + duration + name + '-' + pre + '-' + duration + '-' + pre + '-' + name + '}',
            keyframes: !!(window.CSSKeyframesRule || window[('WebKit|Moz|MS|O').match(new RegExp('(' + pre + ')', 'i'))[1] + 'CSSKeyframesRule'])
        };
    })();

styles.type = keyframes.type = "text/css";
head.appendChild(styles);
head.appendChild(keyframes);

HTMLDocument.prototype.addSelectorListener = HTMLElement.prototype.addSelectorListener = function(selector, fn) {
    var key = selectors[selector],
        listeners = this.selectorListeners = this.selectorListeners || {};

    if (key) events[key].count++;
    else {
        key = selectors[selector] = 'SelectorListener-' + animationCount++;
        var node = document.createTextNode('@' + (prefix.keyframes ? prefix.css : '') + 'keyframes ' + key + ' {' + 'from { outline-color: #fff; } to { outline-color: #000; }' + '}');
        keyframes.appendChild(node);
        styles.sheet.insertRule(selector + prefix.properties.replace(/SelectorListener/g, key), 0);
        events[key] = {
            count: 1,
            selector: selector,
            keyframe: node,
            rule: styles.sheet.cssRules[0]
        };
    }

    if (listeners.count) listeners.count++;
    else {
        listeners.count = 1;
        startNames.forEach(function(name) {
            this.addEventListener(name, startEvent, false);
        }, this);
    }

    (listeners[key] = listeners[key] || []).push(fn);
};

HTMLDocument.prototype.removeSelectorListener = HTMLElement.prototype.removeSelectorListener = function(selector, fn) {
    var listeners = this.selectorListeners || {},
        key = selectors[selector],
        listener = listeners[key] || [],
        index = listener.indexOf(fn);

    if (index > -1) {
        var event = events[selectors[selector]];
        event.count--;
        if (!event.count) {
            styles.sheet.deleteRule(styles.sheet.cssRules.item(event.rule));
            keyframes.removeChild(event.keyframe);
            delete events[key];
            delete selectors[selector];
        }

        listeners.count--;
        listener.splice(index, 1);
        if (!listeners.count) startNames.forEach(function(name) {
            this.removeEventListener(name, startEvent, false);
        }, this);
    }
};

})();

你可以这样称呼:

document.addSelectorListener(selectorsToCheck, function(e) {})