2013-10-31 5 views
0

클릭하면 '임의로 움직이는 스파이더 이미지가 포함 된 할로윈 테마의 애니메이션을 웹 사이트 헤더에 사용하려고합니다. 저는이 작은 프로젝트에 정말로 몸을 싣고 있습니다. 애니메이션을 내가 원하는대로 작동하도록 만들었지 만, 처음 클릭 할 때 애니메이션을 시작하는 방법을 알 수는 없습니다. 이미지는 두 번째 클릭까지 이동하지 않으며, 의도 한대로 실행됩니다.두 번째 클릭까지 jQuery 애니메이션이 시작되지 않습니다

첫 번째 클릭에서 시작하지 않는 애니메이션에 대한 몇 가지 질문에 대한 답변을 살펴 보았지만 스크립트의 문제를 해결하는 데 도움이되지는 않았습니다. 누군가가 올바른 방향으로 나를 가리켜 주시겠습니까?

애니메이션은 jQuery 1.7.2를 실행하는 공급 업체 제어 플랫폼에서 실행해야합니다.

도움을 주셔서 대단히 감사드립니다. 이 사이트가 아니었다면 필자는 스크립트에 관해서는 알지 못했을 것입니다.

HTML :

<div id="hd"> 
    <h1>This is the page title</h1> 
</div> 
<div id="content"> 
<p> 
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec rutrum nibh in 
nunc euismod, eget elementum est consequat. Aenean tempus augue est. Sed elit 
neque, semper a cursus a, semper eu ligula. Nullam tristique augue odio, non 
scelerisque massa eleifend nec. Vivamus mollis purus lacus, vel elementum dui 
vulputate luctus. Sed rutrum nisl non nisl laoreet, sed consequat massa commodo. 
Maecenas consectetur elementum nulla, sed pellentesque ligula gravida eu. 
Suspendisse arcu dui, pretium et fermentum aliquam, eleifend et arcu. Aenean 
placerat porta sapien. Etiam auctor, leo vitae vestibulum mattis, eros risus 
fringilla nibh, id adipiscing turpis ante sed lectus. Quisque turpis metus, 
condimentum eget consectetur eu, pulvinar a massa. Maecenas venenatis eros augue, condimentum porttitor erat varius at. Praesent quis semper erat. 
</p> 
<p> 
Duis magna magna, rutrum non massa non, porttitor auctor turpis. Aliquam at 
aliquet dui. Praesent vestibulum lobortis dapibus. Phasellus hendrerit ut nunc 
vitae placerat. Sed sit amet sollicitudin sapien. Morbi imperdiet arcu ipsum, 
nec congue purus dapibus at. Morbi elementum, nibh in viverra imperdiet, felis 
leo eleifend magna, id facilisis mi leo ut mauris. 
</p> 
</div> 

스크립트 :

여기
$(document).ready(function(){ 
    // add spider image to header 
    $('<img id="spider" src="http://lgimages.s3.amazonaws.com/data/imagemanager/41647/spider2.png" alt="Spider hanging from web" />').prependTo('#hd'); 
    // Note: total height of spider/web image is 620px, so top: -592px positions spider in header area 
    $('#spider').css({ 
     'left' : '125px', 
     'top' : '-592px' 
    }); 

    // dropLow: subtract 87% of window height from total height of spider thread image 
    // we're trying to get spider to drop to lower area of window, but not below visible area 
    var dropLow; 
    var dropMax = $(window).height(); 
    if (dropMax < 600) { 
     dropLow = ((dropMax * .87) - 592); 
     } else { 
     dropLow = "0"; 
     } 

    // generate random number for upper dropdown offset 
    function randomFromInterval(lowerRange,upperRange) { 
     return Math.floor(Math.random()*(upperRange-lowerRange+1)+lowerRange)* -1; 
    } 

    // make spider clickable/tappable 
    $('#hd').on('click', '#spider', function(){ 

     $(this).toggle(function() { 
      // spider drops down to ready position 
      $(this).stop().animate({ 
       top: dropLow - Math.floor((Math.random() * 80) + 1) + 'px' 
      }, 3400); 
     }, function() { 
      // spider rises 
      // randomly generate 1 or -1 as multiplier for a left/right offset 
      var plusOrMinus = Math.random() < 0.5 ? -1 : 1; 
      $(this).stop().animate({ 
       // spider rises until partially hidden 
       top: '-609px' 
      }, 2100, function(){ 
       $(this).delay(1000).animate({ 
        // spider rises until fully hidden 
        top: '-630px' 
       }, 1200); 

       // calculate a new left offset of spider relative to parent div#hd 
       // and add a randomly positive or negative multiplier 
       var myNewLeft = $(this).position().left + (plusOrMinus * 36); 
       // if new left offset is not outside div#hd, move spider there 
       // note that spider is hidden (above window) during this move 
       if (myNewLeft > 0) { 
        $(this).delay(1000).stop().animate({left: myNewLeft + 'px'}); 
       } 

       $(this).delay(1000).stop().animate({ 
        // partially show spider (note top pos change from -630px) 
        top: '-609px' 
       }, 1600, function(){ 
        $(this).delay(1000).stop().animate({ 
         // spider drops a random amount (but stays in header area) 
         top: randomFromInterval(592,495) + 'px' 
        }, 1200); 
       }); 
      }); 
     }); 
    }); 
}); // end ready 

내 스크립트와 JSFiddle입니다.

답변

1

을 처음 클릭 할 때 toggle 처리기가 추가되므로 첫 번째 클릭에서 토글이 실행되지 않습니다.

// make spider clickable/tappable 
$('#spider').toggle(function() { 
     // spider drops down to ready position 
     $(this).stop().animate({ 
      top: dropLow - Math.floor((Math.random() * 80) + 1) + 'px' 
     }, 3400); 
    }, function() { 
     // spider rises 
     // randomly generate 1 or -1 as multiplier for a left/right offset 
     var plusOrMinus = Math.random() < 0.5 ? -1 : 1; 
     $(this).stop().animate({ 
      // spider rises until partially hidden 
      top: '-609px' 
     }, 2100, function(){ 
      $(this).delay(1000).animate({ 
       // spider rises until fully hidden 
       top: '-630px' 
      }, 1200); 

      // calculate a new left offset of spider relative to parent div#hd 
      // and add a randomly positive or negative multiplier 
      var myNewLeft = $(this).position().left + (plusOrMinus * 36); 
      // if new left offset is not outside div#hd, move spider there 
      // note that spider is hidden (above window) during this move 
      if (myNewLeft > 0) { 
       $(this).delay(1000).stop().animate({left: myNewLeft + 'px'}); 
      } 

      $(this).delay(1000).stop().animate({ 
       // partially show spider (note top pos change from -630px) 
       top: '-609px' 
      }, 1600, function(){ 
       $(this).delay(1000).stop().animate({ 
        // spider drops a random amount (but stays in header area) 
        top: randomFromInterval(592,495) + 'px' 
       }, 1200); 
      }); 
     }); 
    }); 

데모 : Fiddle

당신이 어떤 이유로 현재 구조를 유지하려는 경우, 당신은 토글 핸들러가

+0

like in here가 설명하는 당신에게 아룬 감사 등록 후 수동으로 클릭 기능을 트리거하기 위해 시도 할 수 있습니다 내가 뭘 잘못했는지 그리고 작동하는 데모를 제공하는지. 스크립트를 작동시키는 다른 방법에 대해서도 감사드립니다. 스크립트의 시작 부분에서'$ ('# spider'). trigger ('# spider')를 사용해 보았지만 작동하지 않았으므로 클릭 기능을 올바르게 트리거하는 방법을 보여 주셔서 감사합니다. – user2928957

관련 문제