当用户与网页交互,或者脚本程序改动修改网页时,前文提到的一些操作将会重复执行,因为网页的内在结构已经发生了改变。
var $body = $('body');$body.css('padding', '1px'); // reflow, repaint$body.css('color', 'red'); // repaint$body.css('margin', '2px'); // reflow, repaint// only 1 reflow and repaint will actually happen
var $body = $('body');$body.css('padding', '1px');$body.css('padding'); // reading a PRoperty, a forced reflow$body.css('color', 'red');$body.css('margin', '2px');
.has-transition { -webkit-transition: margin-left 1s ease-out;-moz-transition: margin-left 1s ease-out;-o-transition: margin-left 1s ease-out;transition: margin-left 1s ease-out;}
// our element that has a "has-transition" class by defaultvar $targetElem = $('#targetElemId');// remove the transition class$targetElem.removeClass('has-transition');// change the property expecting the transition to be off, as the class is not there// anymore$targetElem.css('margin-left', 100);// put the transition class back$targetElem.addClass('has-transition');// change the property$targetElem.css('margin-left', 50);
// remove the transition class$(this).removeClass('has-transition');// change the property$(this).css('margin-left', 100);// trigger a forced reflow, so that changes in a class/property get applied immediately$(this)[0].offsetHeight; // an example, other properties would work, too// put the transition class back$(this).addClass('has-transition');// change the property$(this).css('margin-left', 50);
div * {...} // bad.list li {...} // bad.list-item {...} // good#list .list-item {...} // good
在你的脚本代码中,尽可能减少DOM操作。缓存所有东西,包括元素属性以及对象(如果它们被重用的话)。当进行复杂的操作时,使用“孤立”元素会更好,之后可以将其加到DOM中(所谓“孤立”元素是与DOM脱离,仅保存在内存中的元素)。
如果你使用jQuery来选择元素,请遵从jQuery选择器最佳实践方案。
为了改变元素的样式,修改“类”的属性是奏效的方法之一。执行这一改变时,处在DOM渲染树的位置越深越好(这还有助于将逻辑与表象脱离)。
尽量只给位置绝对或者固定的元素添加动画效果。
在使用滚动时禁用复杂的悬停动效(比如,在中添加一个额外的不悬停类)
新闻热点
疑难解答