2016-08-14 36 views
0

我有一個開關按鈕。代碼如下:改變父母的風格純js

<div class="switch-radiobutton" data-style="rounded" data-label="on-off"> 
    <input type="radio" id="rb-1" name="rb" checked> 
    <label class="label" for="rb-1"></label> 
</div> 

<div class="switch-radiobutton" data-style="rounded" data-label="on-off"> 
    <input type="radio" id="rb-2" name="rb"> 
    <label class="label" for="rb-2"></label> 
</div> 

的CSS:

/* BASIC SWITCH STYLE */ 

.switch-radiobutton [type='radio'] { 
    visibility: hidden; 
} 

.switch-radiobutton { 
    display: inline-block; 
    position: relative; 
    height: 50px; 
    line-height: 50px; 
    width: 100px; 
    margin-bottom: 30px; 

    background: red; 
    z-index: 1; 
} 

/* LABEL STYLE */ 

.switch-radiobutton:before, 
.switch-radiobutton:after { 
    display: block; 
    position: absolute; 
    top: 0; 
    height: 100%; 
    width: 50%; 
    text-align: center; 
    text-transform: uppercase; 
    font-size: 20px; 
    z-index: 2; 
    color: #fff; 
} 

.switch-radiobutton:before { 
    left: 0; 
} 

.switch-radiobutton:after { 
    right: 0; 
} 

.switch-radiobutton { 

    &:before { 
     content: 'on'; 
    } 

    &:after { 
     content: 'off'; 
    } 
} 

/* SWITCH OFF */ 

.switch-checkbox label, 
.switch-radiobutton label { 
    position: absolute; 
    display: block; 
    top: 4px; 
    left: 4px; 
    height: 42px; 
    width: 42px; 

    background: #fff; 
    cursor: pointer; 
    transition: all .4s ease-in-out; 
    z-index: 3; 
} 

/* SWITCH ON */ 

.switch-checkbox [type='checkbox']:checked + label, 
.switch-radiobutton [type='radio']:checked + label { 
    transform: translate3d(50px,0,0); 
} 

/* SWITCH ROUNDED */ 

.switch-radiobutton[data-style='rounded'], 
.switch-radiobutton[data-style='rounded'] label { 
    border-radius: 50px; 
} 

/* SWITCH SQUARE */ 

.switch-checkbox[data-style='square'], 
.switch-checkbox[data-style='square'] label { 
    border-radius: 5px; 
} 

如何變更的父元素(.switch-單選)的背景輸入與CSS或純JS檢查?沒有jQuery。據我所知,我不能用CSS改變父元素。

回答

0

使用按鈕的onchange調用函數,並將this作爲參數。

在該函數中,使用.parentNode來獲取作爲參數傳遞的節點的父節點。您可以使用.style.backgroundColor()更改背景。

0

var parentObject = yourObject.parentNode(); 
 
parentObject.style.background = "#000";