开发者

Why I can't get this jquery code to work?

I am trying to make the page scroll to post which has specific id e.g. post-21 post-22 etc

But It won't work. what could be wrong with my syntax here please?

// this is number of posts visible. returns e.g. 2
var posts_visible = <?php echo $news['num_per_page']; ?>;
// this is number of more posts loaded. returns e.g. 2
var posts_more = <?php echo $news['num_per_more']; ?>;
// here i calculate the value to know which position should we be at after scroll
var newposition = posts_visible + (posts_more * $.cookie('n开发者_如何学运维_more'));
// here i am trying to set #post-(thepostnumber)
var thispost = '$("#post-' + newposition + '")';
$('html,body').animate({
    scrollTop: thispost.position().top + 'px',
    scrollLeft: thispost.position().left + 'px'
},1000);

Please note that alert(thispost) returns accurately the post with the proper ID i should be at. Just can't get it to work in the animate/scroll. Please help me


Try:

var thispost = $("#post-" + newposition);

You don't want to create a string "$("#post-42")", you want to create the string "#post-42" and pass it to the $ function.


You need just the selector as a string, not the entire $() function call, like this:

var thispost = $("#post-" + newposition).position();
$('html,body').animate({
    scrollTop: thispost.top + 'px',
    scrollLeft: thispost.left + 'px'
},1000);

Also it can be optimized like above...no need to call .position() twice to get the same result.


var thispost = $("#post-"+ newposition);
$('html,body').animate({
    scrollTop: thispost.position().top + 'px',
    scrollLeft: thispost.position().left + 'px'
},1000);


Not sure if this is helpful, but worth sharing. I use this plugin when I want to scroll something http://demos.flesler.com/jquery/scrollTo/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜