html点击向左移动,js实现点击往左移动

Document

*{margin: 0px;padding: 0px;}

ul{width: 10000px;height: 50px;left: 0px; position: relative; list-style: none;transition: width 0.5s;-moz-transition: left 0.5s;-webkit-transition: left 0.5s;-o-transition: left 0.5s;background: deepskyblue;}

li{width: 100px; height: 50px;border-right:1px solid black;text-align: center; line-height: 50px;font-size: 14px;cursor: pointer; float: left;background: deepskyblue;}

  • 第1项
  • 第2项
  • 第3项
  • 第4项
  • 第5项
  • 第6项
  • 第7项
  • 第8项
  • 第9项
  • 第10项
  • 第11项
  • 第12项

var currentElement,frontElement,parent,screen_width,child_offset,childWidth;

frontElement = document.getElementById('id1');

childWidth = frontElement.clientWidth;

frontElement.style.color = "white";

function switchStyle(index){

//上一次的项设置为初始状态颜色

frontElement.style.color = '#333333';

currentElement = document.getElementById(index);

frontElement = currentElement;

parent = document.getElementById('parent');

screen_width = document.body.clientWidth;

//获取单项的偏移值

child_offset = currentElement.offsetLeft;

//当前项被设置为白色字体

currentElement.style.color = "white"

//核心,屏幕宽除以2,当前被点击的项大于屏幕的一半则进入,然后设置偏移值,偏移值为当前项偏移值减去屏幕的一半,此时当前项的左端对齐屏幕的中间,所以还需在加上当前项的一半,才能实现居中效果,还有不明白的可以在下面评论

if(screen_width/2

parent.style.left = -((child_offset+childWidth/2) - screen_width/2)+"px";

}else{

this.parent.style.left = '0px'

}

}

以下是vue项目(vue-cli搭建)的实现方式,只提供jjs部分(带有es6语法),也是核心部分

export default{

data(){

return{

currentElement:null,

frontElement:null,

parent:null,

screen_width:null,

child_offset:null,

childWidth:null,

currentElement:null,

}

},

mounted:function(){

this.parent = document.getElementById('parent');

this.screen_width = document.body.clientWidth;

this.frontElement = document.getElementById('id1');

this.childWidth = this.frontElement.clientWidth;

this.frontElement.style.color = "white";

},

methods:{

switchStyle:function(index){

this.frontElement.style.color = '#19ddff';

this.currentElement = document.getElementById(index);

this.frontElement = this.currentElement;

this.child_offset = this.currentElement.offsetLeft;

this.currentElement.style.color = "white"

if(this.screen_width/2

this.parent.style.left = -((this.child_offset+this.childWidth/2) - this.screen_width/2)+"px";

}else{

this.parent.style.left = '0px'

}

}

}

}