繁体   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