document.body.classList.add (‘hasJS’);
document.body.classList.remove (‘hasJS’);
document.body.classList.toggle (‘hasJS’);
document.body.classList.contains (‘hasJS’);
八、CSS
jQuery 的 css 方法,用来设置网页元素的样式。
$(node) .css ( “color”, “red” );
DOM 元素有一个 style 属性,可以直接操作。
element.style.color = “red”;;
// or
element.style.cssText += ‘color:red’;
九、数据储存
jQuery 对象可以储存数据。
$(“body”) .data (“foo”, 52);
HTML 5 有一个 dataset 对象,也有类似的功能(IE 10 不支持),不过只能保存字符串。
element.dataset.user = JSON.stringify (user);
element.dataset.score = score;
十、Ajax
jQuery 的 Ajax 方法,用于异步操作。
$.ajax ({
type: “POST”,
url: “some.php”,
data: { name: “John”, location: “Boston” }
}) .done (function ( msg ) {
alert ( “Data Saved: ” + msg );
});
我们可以定义一个 request 函数,模拟 Ajax 方法。
function request (type, url, opts, callback) {
var xhr = new XMLHttpRequest ();
if (typeof opts === ‘function’) {
callback = opts;
opts = null;
}
xhr.open (type, url);
var fd = new FormData ();
if (type === ‘POST’ && opts) {
for (var key in opts) {
fd.append (key, JSON.stringify (opts[key]));
}
}
xhr.onload = function () {
callback (JSON.parse (xhr.response));
};
xhr.send (opts ? fd : null);
}
然后,基于 request 函数,模拟 jQuery 的 get 和 post 方法。
var get = request.bind (this, ‘GET’);
var post = request.bind (this, ‘POST’);
十一、动画
jQuery 的 animate 方法,用于生成动画效果。
$foo.animate (‘slow’, { x: ‘+=10px’ });
jQuery 的动画效果,很大部分基于 DOM。但是目前,CSS 3 的动画远比 DOM 强大,所以可以把动画效果写进 CSS,然后通过操作 DOM 元素的 class,来展示动画。
foo.classList.add (‘animate’);
如果需要对动画使用回调函数,CSS 3 也定义了相应的事件。
el.addEventListener (“webkitTransitionEnd”, transitionEnded);
el.addEventListener (“transitionend”, transitionEnded);
十二、替代方案










