0

Ok so here's the problem, this is a little hairy so I'll try to break it down as much as possible:

I have a link:

http://www.example.com/stuff.html#tag

Now that link leads to a page with multiple divs that are hidden and expand when clicked. I know I say it's slideDown() in the title, but it's not really. The code I'm using was a fix for a bug I was encountering with the slideDown, it would hiccup and jerk about 10 px up after the animation completed, this is what the code I have looks like:

This is the .js

var $div = $('#option1');
var height = $div.height();
$div.hide().css({ height : 0 });

$('.xpand').click(function () {
  if ( $div.is(':visible') ) {
    $div.animate({ height: 0 }, { duration: 200, complete: function () {
        $div.hide();
      } 
    });
  } else {
    $div.show().animate({ height : height }, { duration: 200 });
  }

  return false;
});

and the html

<div class="topic xpand">
  <div class="img">
    <img src="example.html" />
  </div>
  <a href=""><div class="plus_sign"></div></a>
  <div class="context">
    <p><a href="">Title</a></p>
  </div>
</div>
<div class="wrapper">
  <div id="option1"><p style="margin:0px">
    <p>
      <a name="tag"></a>CONTENT GOES HERE
    </p>
  </div>
</div>

Now what I need to do is have the relevant section expand based on which #tag is appended to the link and hopefully also have the page center on it as well.

I've been bashing my head against the wall for a while now and all I've got so far is this:

if(window.location.hash) {
      var hash = window.location.hash.substring(1); 
      alert("Hash test, current hash is: " + hash);
      // traverse the dom and find div to expand
      // activate code to slide content down
      // move the window to the anchor tag location
  } else {
        alert ("no hash");
      // No hash found
  }

Am I even going about this in the right way?

Any input even pointing me in a better direction would be appreciated!

4

1 回答 1

1

jQuery 擅长 dom 遍历。鉴于hash您从 URL 中取出的值,您可以简单地选择与选择器匹配的最接近的div 并将其向下滑动。

$('a[name=' + hash + ']').closest('div').slideDown();

如果您尝试使用包装类向下滑动该 div,则可以改用该包装类.closest('.wrapper')

于 2013-06-05T20:10:11.783 回答