[英]Convert Javascript code, that changes DOM element's background color, to JQuery
我是 jQuery 新手,仍在學習。 我的問題是我不知道如何將以下 javascript 代碼轉換為 jQuery。
Java腳本:
document.getElementsByClassName('p-bg')[0].style.backgroundColor = '#'+this.color
在此先感謝各位。
順便說一下,這是完整的代碼:
<input class="color" onchange="document.getElementsByClassName('p-bg')[0].style.backgroundColor = '#'+this.color">
再次感謝
$(".color")
jQuery 類選擇器
.change
.change() 表單事件
.eq()
.eq() 過濾元素
.css()
.css() 操作
$(".color").change(function(){
$(".p-bg").eq(0).css("background-color", $(this).css("color"));
})
注意jQuery 中的document.getElementsByClassName('p-bg')[0]
等價於$(".p-bg").eq(0)
請記住,在jQuery
,必須加載DOM才能開始工作,例如:
$(document).ready(function(){
//You jQuery code here...
})
$('.p-bg:first').css('backgroundColor','"#"+this.color');
change
函數綁定了一個函數,該函數將執行選擇集的 onchange,在我們的例子中是所有 class = 'color' 的元素。
函數中的$(this)
將在選擇中引用當前 DOM 元素,因此通過這種方式我們可以捕獲它的 color 屬性。
$('.p-bg:first')
,這里我們選擇所有類 p-bg 的元素,並使用 :first 偽類選擇器獲取第一個元素,然后使用css
jquery 函數,我們定義第一個參數'backgroundColor'
的 css 屬性和第二個參數中的屬性值使用當前元素$(this).css("color")
另一個 css 屬性( $(this).css("color")
。
當我們使用帶有一個參數的 css 函數時,它將返回值,使用 2 個參數我們將設置該值。
下面的代碼將是jquery中的變化。
$(".color").change(function(){
$('.p-bg:first').css('backgroundColor', $(this).css("color"));
});
如果你真的想看起來像你在 html 中使用過的 Js,這對你有用(只有一行代碼):
<input class="color" onchange="$(this).css('background-color',$(this).css('color'))">
但我會建議您創建一個更改功能,然后對其進行處理。
網址:
<input class="color">
腳本:
<script>
$('.color').on('change',function(){
$(this).css('background-color',$(this).css('color'));
});
</script>
解釋:
$(this)
將為您獲取此元素。 然后使用.css('background-color',$(this).css('color'))
將其顏色分配給它的背景。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.