簡體   English   中英

如何設置由javascript動態創建的元素的樣式

[英]How do I style an element dynamically created by javascript

我是前端開發的新手。 我正在嘗試編寫注釋工具。 下圖顯示了一個示例屏幕。 用戶選擇句子后,在右側欄的與突出顯示的句子相同的水平位置處添加注釋框。

我想編輯新創建的html元素的樣式,但是我該怎么做呢?

在此處輸入圖片說明

這是我的html結構:

  <section id="main">
        <div class="row">
            <div class="small-8 large-8 columns"id="rawdata">

                <p> <span class="sentence">2:22 So, last time I was here, I don't know if I told you this, but, um, we kind of did a "I like, I wish" activity on paper, about things that you like about studio, and things that you wish would change.</span><span class="sentence"> Um, do you want to share any of those thoughts now, so maybe we can talk about them? [name], I have yours if you want to look at it again.</span></p>
                <p><span class="sentence">2:47 I forgot to add something.</span></p>
                <p><span class="sentence">2:54 Well, I don't know, in terms of what I dislike about studio.</span></p>
                <p><span class="sentence">2:57 So, some people wrote in theirs that, um, they dislike how cluttered it gets.</span></p>

                <p><span class="sentence">5:09 I don't get bothered.</span>< <span class="sentence">I like the draftiness, I'm a little...</span><span class="sentence"> I'm one of the ones that opens the windows, and like—</span></p>
            </div>
            <div class="small-4 large-4 columns" id="annotations"><p></p>
            </div>
        </div>
    </section>

用於選擇句子和添加注釋的JS:

 <script>
    $('.sentence').click(function() {
        $(this).toggleClass('sentenceStyle');
        var y = $(this).offset().top;
        y = parseInt(y) + 'px';

        var para = document.createElement("p");
        $("#annotations").append(para);
        para.innerHTML="this is an annotation";
        para.css('color','yellow');
    });
</script>

這是小提琴: http : //jsfiddle.net/yujuns/HDe6v/3/

您在jQuery和本機腳本之間進行了一些切換。

css()是jQuery方法,而para是DOM元素。

學習使用瀏覽器控制台/開發人員工具查找錯誤。 您應該為para.css()看到一個。

我建議要么使用所有簡單的腳本方法,要么將所有jQuery方法用於DOM操作,並盡量不要混合使用。

使用jQuery,您可以使用以下命令創建相同的p

var para = $('<p>').text("this is an annotation").css('color','yellow');

使用代碼,您必須更改需要從para創建jQuery對象才能使用css()的樣式。

$(para).css('color','yellow');

另外,您也可以使用本機屬性直接在DOM元素本身上更改樣式

您可以在jquery中使用css函數來執行此操作...

$(para).css({
   'color':'yellow',
   'font-size':'20px'
});

這些css屬性嵌套在style屬性的元素中。

由於para不是jquery對象,因此它給出了錯誤,

您可以使用多個替代項,

var para = $('<p>').text("this is an annotation").css('color','yellow');

var paraHTMLObject= para.get(0)

要么

 var para = document.createElement("p");


$("#annotations").append(para);



 para.innerHTML="this is an annotation";



para.style="color:yellow"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM