這段代碼怎么就無(wú)法實(shí)現(xiàn)鏈?zhǔn)絼?dòng)畫
下面的代碼無(wú)法實(shí)現(xiàn)鏈?zhǔn)絼?dòng)畫是怎么回事,瀏覽器提示橫線有誤,這里一直都是這樣啊怎么就錯(cuò)了
?function getStyle(obj,attr){
? ? ? ? if(obj.currentStyle){
? ? ? ? return obj.currentStyle[attr];
? ? ? ? }else{
? ? ? ? return getComputedStyle(obj,false)[attr];
? ? ? ? }
? ? ? ?}
JS:
function startMove(obj,attr,target,fn){
? ? ? ? clearInterval(obj.timer);
? ? ? ? ? var speed=0;
? ? ? ? ? obj.timer = setInterval(function(){
? ? ? ? ? var icur = 0 ;
? ? ? ? ? if(attr=='opacity'){
? ? ? ? ? icur = Math.round(parseFloat(getStyle(obj,attr))*100);
? ? ? ? ? }else{
? ? ? ? ? icur = parseInt(getStyle(obj,attr));
? ? ? ? ? }
? ? ? ? ?
? ? ? ? ? speed = (target-icur)/8;
? ? ? ? ? speed = speed>0?Math.ceil(speed):Math.floor(speed);
? ? ? ? ? if(icur==target){
? ? ? ? ? clearInterval(obj.timer);
? ? ? ? ? if(fn){
? ? ? ? ? fn();
? ? ? ? ? }
? ? ? ? ?
? ? ? ? ? }else{
? ? ? ? ? if(attr=='opacity'){
? ? ? ? ? ? ? ? ? ?obj.style.opacity = (icur+speed)/100;
? ? ? ? ? ? ? ? ? ?obj.style.filter = 'alpha(opacity:'+(icur+speed)+')';
? ? ? ? ? }else{
? ? ? ? ? ? obj.style[attr] = icur+speed+'px';
? ? ? ? ? }
? ? ? ? ? ? ? ?
? ? ? ? ? }
? ? ? ? ? },30);
? ? ? ?}
? ? ? ?//獲取屬性
? ? ? ?function getStyle(obj,attr){
? ? ? ? if(obj.currentStyle){
? ? ? ? return obj.currentStyle[attr];
? ? ? ? }else{
? ? ? ? return getComputedStyle(obj,false)[attr];
? ? ? ? }
? ? ? ?}
HTML:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>
</title>
<style type="text/css">
? ? ? ?#test{
? ? ? ? height: 200px;
? ? ? ? width: 200px;
? ? ? ? border: 2px solid red;
? ? ? ? background: red;
? ? ? ? opacity: 0.3;
? ? ? ? filter:alpha(opacity:30);
? ? ? ?}
</style>
? <script src = "linkspeed.js"></script>
<script type="text/javascript">
? ? ? ?window.onload = function(){
? ? ? ? var test = document.getElementById('test');
? ? ? ? test.onmouseover = function(){
? ? ? ? ? startMove(this,'width',400,function(){
? ? ? ? ? ?startMove(this,'height',400,function(){
? ? ? ? ? ? startMove(this,'opacity',100);
? ? ? ? ? ?})
? ? ? ? ? });
? ? ? ? }
? ? ? ?}
? ? ? ?
</script>
</head>
<body>
<div id="test"></div>
</body>
</html>
2017-02-25
startMove(this,'width',400,function(){
?startMove(this,'height',400,function(){
startMove(this,'opacity',100);
把后兩個(gè)this換成你定義的test。
判斷 this 指向誰(shuí),看執(zhí)行時(shí)而非定義時(shí),只要函數(shù)(function)沒有綁定在對(duì)象上調(diào)用,它的 this 就是 window。
你會(huì)發(fā)現(xiàn)按照你原來(lái)的代碼寫的話,它只變了width,height和opacity都沒有變,顯示的錯(cuò)誤是window.getStyle...,這說(shuō)明后兩個(gè)startMove()函數(shù)全都去操做window對(duì)象了,而不是id為test的div。