2017-05-26 16 views
1

我想在按鈕上顯示不允許的光標選項。 我想要在javascript中使用CSS來完成此操作,當我的if條件滿足時。如何在JavaScript中使用CSS

我的按鈕代碼是這樣的:

<button type="button" id="myBtn" class="btn btn-success" title=""></button> 

這是我的,如果條件:

if (percent <= 99) 
{ 
//using class name: 
document.getElementsByClassName("btn").style.cursor = "not-allowed"; 

} 
else 
{ 
//using id: 
document.getElementsById("mybtn").style.cursor = "allowed"; 

} 
+0

誰能幫助我,我應該如何使用CSS按鈕在JavaScript中。 – Deb

+2

'getElementsByClassName'返回集合,因此你應該使用'loop'或者如果你的目標是第一個元素,然後'[0]'通過'getElementsByClassName',然後應用樣式..'getElementsById'應該可以正常工作。糾正錯字,它是'getElementById',它是單數的,因爲ID總是唯一的。 – Rayon

+0

僅適用於myBtn: 'myBtn.style.cursor = percent <= 99? 'not-allowed':'default';' –

回答

0

是根據你的問題@Rayon說的是完全正確的。你必須在你的情況下使用循環,因爲它返回一組對象。

如果你不想使用循環,仍然想實現這一點,那麼最終的解決方案是使用JQuery庫。使用Jquery庫你可以這樣做。

if (percent <= 99) { $(".btn").css("cursor", "not-allowed");} 
else {$("#mybtn").css("cursor", "allowed");} 

這將適用於頁面中的所有元素。

+0

Javascript,而不是jQuery – Aslam

+0

我認爲你應該在評論之前先閱讀答案。我已經在我的答覆中已經接受,這不是根據您的要求提供的解決方案,這意味着我正在向Deb先生提出建議,即有另一種方法可以實現這一點。 –

+0

我讀了你的答案。我沒有看到任何寫這樣的東西。同樣的問題是在Javascript中使用CSS。而且使用jQuery並不是最終解決方案。和平:) – Aslam

0

光標樣式屬性沒有允許。相反,您可以使用默認

if (percent <= 99) 
{ 
//using class name: 
document.getElementsByClassName("btn")[0].style.cursor = "not-allowed"; 
//or using id 
document.getElementsById("btn").style.cursor = "not-allowed"; 
} 
else 
{ 
//using class name: 
document.getElementsByClassName("btn")[0].style.cursor = "default"; 
//or using id 
document.getElementsById("btn").style.cursor = "default"; 

} 
-1

這裏是本機Javascript中的代碼,以幫助您入門。

var buttons = document.querySelectorAll(".btn"); 

buttons.forEach(button => { 
    percent <= 99 ? (button.style.cursor = "not-allowed") : (button.style.cursor = "allowed"); 
}); 
-1

我不認爲爲什麼它不工作,但我們可以通過添加類 做了你的風格類應該是:

.btn-disable 
    { 
    pointer-events: none; 
    cursor: not-allowed; 
    filter: alpha(opacity=65); 
    -webkit-box-shadow: none; 
    box-shadow: none; 
    opacity: .65; 
    } 

if (percent <= 99) 
{ 
//using class name: 
document.getElementsByClassName("btn").className += " btn-disable"; 
} 
else 
{ 
//using id: 
document.getElementById("myBtn").classList.remove("btn-disable"); 

}