根据链接#extension

时间:2015-07-20 21:15:11

标签: javascript jquery

是否可以将jQuery设置为捕获#链接并根据其拾取的动画显示动画?

  

示例:

     

点击链接1> /index.php#1 = pulsate div 1

     

点击链接2> /index.php#2 = pulsate div 2

     

点击链接3> /index.php#3 = pulsate div 3

我目前有一个指南/规则页面,当人们被特定链接带到那里时,它希望它突出显示正确的内容。我理解基本的jQuery动画,只是没有从父页面给它们规则。

4 个答案:

答案 0 :(得分:2)

1。从URI

读取哈希

JS window.location.hash会在 HTML5

中读取"#1"这样的哈希值,这是有效ID
jQuery(function($) {
   $( window.location.hash ).addClass("pulsate");
});

您有 DIV 元素,例如

<div id="div1">I'm DIV 1</div>

CSS 类一样,

.pulsate {
  /* other styles here... */
  animation: pulsate 0.5s ease-in-out;
  animation-iteration-count: 5;                                    /* Pulsate 5 times */
}
@keyframes pulsate {
  0%    {transform: scale(1);}
  50%   {transform: scale(1.2);}
}

2。从点击链接中读取哈希

如果您对阅读URI的哈希不感兴趣,但您只有像

这样的LInks
<a class="animateButton" href="#div1">Animate DIV1</a>

这就是你所需要的:

&#13;
&#13;
$(".animateButton").on("click", function(){
  $( this.hash ).addClass("pulsate").on("animationend", function(){
    $(this).removeClass("pulsate");
  });
});
&#13;
.pulsate {
  background: orange;
  animation: pulsate 0.5s ease-in-out;
  transition:0.5s;
  animation-iteration-count: 3; 
}
@-webkit-keyframes pulsate {
  0%    {transform: scale(1);}
  50%  {transform: scale(1.1);}
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="animateButton" href="#1">#1</a>
<a class="animateButton" href="#2">#2</a>
<a class="animateButton" href="#3">#3</a>

<div id="1">I'm DIV #1</div>
<div id="2">I'm DIV #2</div>
<div id="3">I'm DIV #3</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

它不是来自父母页面&#34;&#34; 的规则。您可以使用location.hash

从网页的网址中获取哈希参数
//index.php#1
location.hash //-> will return #1

//index.php#2
location.hash //-> will return #2

然后,您可以直接在jQuery选择器中选择$(location.hash)。这将使您能够为目标div设置动画。

$(document).ready(function() {
    //Do your animation
    $(location.hash).animate(/*...*/)
});

<强>观测值:

请记住,带有数字ID的div仅在HTML5中有效

答案 2 :(得分:1)

这是你玩的fiddle。我没有添加动画,但作为练习留给你。 =]

HTML

$("a").on('click', function(event){
    var t = event.target.toString();
    if (t.endsWith('1')){
        alert('animation 1');
    } else if (t.endsWith('2')){
            alert('animation 2');
    } else if (t.endsWith('3')){
            alert('animation 3');
    }
});

JS

T

答案 3 :(得分:1)

你必须听哈希变化。 尝试使用像hashchange这样的插件。

$(window).hashchange((function(){
      var hash = window.location.hash.replace("#",'');
  // remove previous animation from element if there's one

  if(hash) {
    // do your animation adding class or with pure jquery
  }
  return arguments.callee;  // return itself as the hashchange handler
})( )); // exec the first time and then at each hash changes

记得从prevuos pulsating元素中移除类或javascript动画。

jQuery hashchange plugin