简体   繁体   English

使用createElement将新段落添加到现有段落并保持相同的CSS

[英]using createElement to add a new paragraph to existing paragraph and keeping same css

I am using javascript to add a new paragraph just below the existing paragraph on the html code page. 我正在使用javascript在html代码页上现有段落的正下方添加一个新段落。 The new paragraph is not following the same css as the first one. 新段落没有遵循与第一段相同的CSS。 here is a link to the source code http://students.cpcc.edu/~lplumme2/web115/swtl/seventh10chaptersexamples.html 这是源代码的链接http://students.cpcc.edu/~lplumme2/web115/swtl/seventh10chaptersexamples.html

 function seventh10() { alert("let's start the javascipt"); var para = document.createElement("p"); var t = document.createTextNode("We have different ways of teaching you. Our office location is designed to look like a student lab.We can work with you one on one there or you can meet you somewhere else or we can even come to your house"); para.appendChild(t); document.getElementById("myBlog").appendChild(para); } seventh10(); 
 <p id="myBlog"> We have a variety of subjects and software that we can help you<br> improve your skills on. We teach from brand new levels to just helping<br> build on what you already know.<br> </p> 

Your code adds the new <p> inside the existing <p> . 您的代码添加新的<p>现有的内部 <p> That means that the left margin CSS rule applies for the second one with respect to the container <p> that's also got a big left margin. 这意味着相对于容器<p> ,左边距CSS规则适用于第二条规则,该容器有很大的左边距。

To prevent that, you can add the new <p> to the element that contains the existing <p> . 为防止这种情况,可以将新的<p>添加到包含现有<p>的元素中。

Adding a <p> as a child of another <p> is kind-of unnatural anyway. 无论如何,将<p>添加为另一个<p>的子代都是不自然的。 The browser will let you manipulate the DOM pretty much any way you like, but the HTML parser won't do that. 浏览器可以让您以自己喜欢的任何方式来操作DOM,但是HTML解析器不会这样做。 A <p> can't contain block content under HTML rules. <p>不能包含HTML规则下的阻止内容。

The p element has some value set as margin-left . p元素的某个值设置为margin-left Since you are appending the the newly created p to another p , this p again taking the default margin-left set. 由于您要将新创建的p追加到另一个p ,因此该p再次采用默认的margin-left设置。

To fix the issue, you can set the marginLeft property to 0 for the newly created paragraph. 若要解决此问题,可以将新创建​​的段落的marginLeft属性设置为0

para.style.marginLeft = '0px';


function seventh10() {
  ....
  para.style.marginLeft = '0px';
  para.appendChild(t);
  ....

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM