HTML中的多个类属性 [英] Multiple class attributes in HTML

查看:129
本文介绍了HTML中的多个类属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当元素有多个 class 属性时会发生什么?

What happens when an element has multiple class attributes?

<div id="test" class="one two three" class="four">

我试图添加一个类到 post_class ;

I'm trying to add a class to the output of post_class(); in a WordPress plugin, but the function itself is creating the entire part class="one two three"

它相当于 class =one two three four
或者第一次或第二次胜利?
或者是未定义的行为,在这种情况下,主要的浏览器做什么?

Is it equivalent to class="one two three four"? Or does the first or second win? Or is it undefined behaviour, in which case what do the major browsers do?

如果你知道正确的方式添加一个类到这个代码片段插件),那么这也是值得赞赏的!

If you know the correct way of adding a class to this snippet (WordPress plugin), then that would also be appreciated!

<div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>


推荐答案


元素有多个类属性?

What happens when an element has multiple class attributes?

当一个元素被声明多次时, ,在行为方面,第一个值将覆盖同一属性的所有后续值。所以在这种情况下,你的元素将只有类一两三

When an attribute is declared multiple times for a single element (which is invalid HTML, by the way), behavior-wise the first value will override all subsequent values for the same attribute. So in this case, your element will only have the classes one two three.

a href =http://www.w3.org/TR/html5/syntax.html#attribute-name-state> HTML5规范,8.2.4.35属性名称状态,...如果有已经是具有完全相同名称的[element]上的属性,则这是一个解析错误,必须删除新属性...

This behavior is explained in the HTML5 spec, 8.2.4.35 Attribute name state, "... if there is already an attribute on the [element] with the exact same name, then this is a parse error and the new attribute must be removed..."


如果你知道向这个片段(WordPress插件)添加类的正确方法,那么这也是值得赞赏的!

If you know the correct way of adding a class to this snippet (WordPress plugin), then that would also be appreciated!

通常,如果你需要动态添加自定义类到你的WordPress的帖子,你钩上 post_class 过滤器,并操作 $ classes 数组。这里是我的主题大致的样子:

Typically, if you need to add custom classes dynamically to your WordPress posts, you hook onto the post_class filter and manipulate the $classes array as necessary. Here's what it roughly looks like in my themes:

function nv_post_class( $classes ) {
    // Most recent post on the front page
    global $count;
    if ( is_home() && 1 == $count )
        $classes[] = 'latest-post';

    return $classes;
}

add_filter( 'post_class', 'nv_post_class' );

如果只需要添加一个或多个静态类,则直接将它们作为空格分隔的字符串 post_class()

If you only need to add one or more static classes, pass them as a space-delimited string directly to post_class():

<div id="post-<?php the_ID(); ?>" <?php post_class( 'myclass1 myclass2' ); ?>>

有关 WordPress Codex

这篇关于HTML中的多个类属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆