样式<li>如果选中radiobutton - Howto?</li>

时间:2014-06-27 23:41:40

标签: javascript jquery html css

我正试图检查<li>是否检查了无线电按钮。

以下是我要更改的插件代码:

<div class="gift-certificate-show-form">
    <p><?php _e( 'Vem vill du skicka ditt presentkort till?', 'wc_smart_coupons' ); ?></p>
    <ul class="show_hide_list" style="list-style-type: none;">
        <li>
            <input type="radio" id="hide_form" name="is_gift" value="no" checked="checked" />
            <label for="hide_form">
                <?php _e( 'Skicka presentkortet till mig!', 'wc_smart_coupons' ); ?>
            </label>
        </li>
        <li>
            <input type="radio" id="show_form" name="is_gift" value="yes" />
            <label for="show_form">
                <?php _e( 'Till någon annan!', 'wc_smart_coupons' ); ?>
            </label>
        </li>
    </ul>
</div>

我将如何实现这一目标?

我试过了:`

show_hide_list input[type="radio"]:checked + label {
    background: beige !important;

但只有背景文字。我希望整个<li>高亮。感谢

2 个答案:

答案 0 :(得分:2)

这可以在CSS 4中使用:has选择器,就像在jQuery中一样。但是,截至目前,没有浏览器实现它,所以你必须使用JavaScript(jQuery将完成这项工作)

这里有一些代码,只需添加一个highlighted CSS类与您的风格:

$(".gift-certificate-show-form :radio").on("click", function() {
    $(this).closest(".gift-certificate-show-form").find("li").removeClass("highlighted");
    $(this).closest("li").addClass("highlighted");
});

完成这项工作的另一种方式,因为我刚刚注意到表单实际上是从一个已检查的无线电开始的:

$(function() {
    var updateHighlight = function() {
        $(".gift-certificate-show-form")
            .find("li")
                .removeClass("highlighted")
            .end()
            .find("li:has(:radio:checked)")
                .addClass("highlighted");
    };

    updateHighlight();
    $(".gift-certificate-show-form :radio").on("click", function() {
        updateHighlight();
    });
});

在这里小提琴:http://jsfiddle.net/LucasTrz/Yc6Qj/1/

不要忘记添加对jQuery的引用。

答案 1 :(得分:0)

如果你想要一个只有CSS的解决方案,那么尝试将单选按钮设置为块级元素(通过设置display: block;)并将其宽度设置为等于容器(通过设置width: 100%;)并设置样式根据是否检查(通过指定input[type="radio"]:checked选择器的样式规则),您希望以何种方式。

相关问题