Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/85.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Classname javascript是否与addClass jQuery相同?_Javascript_Jquery - Fatal编程技术网

Classname javascript是否与addClass jQuery相同?

Classname javascript是否与addClass jQuery相同?,javascript,jquery,Javascript,Jquery,我想知道javascript中的classname是否与jQuery中的addClass相同。 我想将以下函数更改为jQuery: function slidePageFrom(page, from) { // Position the page at the starting position of the animation page.className = "page " + from; // Position the new page an

我想知道javascript中的
classname
是否与jQuery中的
addClass
相同。 我想将以下函数更改为jQuery:

function slidePageFrom(page, from) {
        // Position the page at the starting position of the animation
        page.className = "page " + from;
        // Position the new page and the current page at the ending position of their animation with a transition class indicating the duration of the animation
        page.className ="page transition center";
        currentPage.className = "page transition " + (from === "left" ? "right" : "left");
        currentPage = page;
    }
HTML:


主页
第1页
第2页

DOM元素节点的
className
属性是该节点上所有类的一个以空格分隔的列表。如果一个元素有类“a”、“b”和“c”,那么
.className
将是
“ABC”
(可能是另一种顺序,因为顺序无关紧要)

相比之下,jQuery
.addClass()
.removeClass()
函数执行它们所说的操作:添加类(如果不存在)或删除类(如果存在)。这些操作只影响所涉及的类别;其他人则留在原地

因此,答案是jQuery方法为您提供了一个抽象来操作
.className
属性,但是说它们是“相同”是不正确的

请注意,在函数中,使用以下前两条语句:

    page.className = "page " + from;
    // Position the new page and the current page at the ending position of their animation with a transition class indicating the duration of the animation
    page.className ="page transition center";
.className
属性的第二个赋值将完全覆盖第一条语句在其中放置的值。换句话说,不管
from
的值是多少,第二条语句之后的
page.className
的值将始终
“页面转换中心”
。另一方面,如果第二条语句使用了jQuery
.addClass()


然后,无论
from
中的类名是什么,它都会存在。

该函数中的第二条语句完全取消了第一条语句所做的操作。jquery addClass将保留旧类并添加新类您还可以使用removeClass删除class@Pointy这就是它的本意;这是一个动画(CSS转换的问题),它不是100%相同,因为设置
.classname
会覆盖当前的类名列表,而jQuery的
.addClass
只是添加到列表中,就像本机的
.classList.add
方法一样。您可以使用
$(page).attr('class',…)
来设置保持相同lgic的class属性,但这看起来像是不必要的开销。@Tyblitz设置并立即重置
.className
将没有视觉效果;换句话说,浏览器不会立即更新页面布局。
    page.className = "page " + from;
    // Position the new page and the current page at the ending position of their animation with a transition class indicating the duration of the animation
    page.className ="page transition center";
    $(page).addClass("page transition center");