浏览器重绘和回流

以前写代码不太注意浏览器回流和重绘问题,这次掉坑里了,必须解决这个问题.

在项目中,用angular的derective写了一个组件,组件的background-image随着选中变化,并且组件的大小也会变化 ,之前的代码使用了下面写法:

dragBoxElement.style.top = "" + (newVal*$scope.dragModel.top) + "px"; //造成浏览器回流
dragBoxElement.style.left = "" + (newVal*$scope.dragModel.left) + "px";
dragBoxElement.style.width = "" + (newVal*$scope.dragModel.width) + "px";
dragBoxElement.style.height = "" + (newVal*$scope.dragModel.height) + "px";

然后再给background: url( {{dragModel.thumbnail}}中的dragModel.thumbnail赋值,修改背景图片,

这段代码会让浏览器先回流,再重绘,重绘的时候背景图片的大小就不会使用之前设置的大小,而是按照渲染准则(css中初始规定)的大小显示。

最终的解决办法就是让将这些引起回流和重绘的操作,构建为一个一个整体样式,让浏览器只 回流重绘一次,修改如下:

var top = "" + ($scope.scaleRatio*$scope.dragModel.top) + "px"; //按照比例显示素材宽高
var left = "" + ($scope.scaleRatio*$scope.dragModel.left) + "px";
var width = "" + ($scope.scaleRatio*$scope.dragModel.width) + "px";
var height = "" + ($scope.scaleRatio*$scope.dragModel.height) + "px";
var thumbnail= $scope.dragModel.materials[i].type==="IMAGE"?$scope.dragModel.materials[i].originalFilePath:$scope.dragModel.materials[i].filePath;
var cssText="top:"+top+";left:"+left+";width:"+width+";height:"+height+";background-image:"+"url("+thumbnail+");"+"background-size: 100% 100%;";
dragBoxElement.style.cssText=cssText;

dragBoxElement.style.cssText的使用可以减少回流重绘的次数;

关于重绘和回流请参考:http://www.css88.com/archives/4996

select中option选项的上下移动,添加、删除操作参考代码:

http://blog.csdn.net/jadyer/article/details/16804279

 

posted @ 2017-04-27 13:27  夏日雪  阅读(295)  评论(0编辑  收藏  举报