应用场景:
"灵感编程" 网站的后台, 在添加记录之后, body 自动滚动从而定位到该行记录 (方便继续添加);
使用的代码:
所在位置:
D:\yfwww\kuihua\Application\Tpl\Houtai\Public\js\Common\init.js
相关代码:
- $(function(){
- var last_top=300;
- // var last_top=1000;
- var gundong_top=0;
- // 需要移动的距离
- var obj=$('.table tr[class=current_item]');
- console.log(obj);
- // if (obj.length!=0) {
- // if (obj) {
- if (obj.offset().top) {
- // if (obj != undefined) {
- var self_top=obj.offset().top;
- // console.log('self_top='+self_top);
- if (self_top>last_top) {
- gundong_top=self_top-last_top;
- }
- $('html,body').animate({
- scrollTop: gundong_top,
- }, 400,"swing",function (){
- });
- }
- });
使用其他方式, 均提示这样的错误:
解决方案:
从上面 console.log() 中可以看到, 如果没找到, 这 length 为 0, 所以要使用 length 是否为 0 的检测方式才可以正确:
即: 最后正确的代码为:
- $(function(){
- var last_top=300;
- var gundong_top=0;
- // 需要移动的距离
- var obj=$('.table tr[class=current_item]');
- if (obj.length!=0) {
- var self_top=obj.offset().top;
- if (self_top>last_top) {
- gundong_top=self_top-last_top;
- }
- $('html,body').animate({
- scrollTop: gundong_top,
- }, 400,"swing",function (){
- });
- }
- });
成功执行后, 可以正确定位, 如图:
本文代码查询:
详细查看地址:
http://www.phpkhbd.com/note/121/2875
来源: http://www.qdfuns.com/article/39237/0b00c4df505a824f417a48039f68f0cb.html