1 回答

TA貢獻1789條經驗 獲得超8個贊
JS問題:
首先,當您調用 時document.createElement()
,您不小心傳入了容器的名稱。相反,您應該傳入button
,如下所示:const btn = document.createElement('button');
接下來,您不需要創建文本節點。btn.innerText = name
會工作得很好;)
最后,你不小心在你的new ParagraphChanger(document.getElementById('target_p;'));
.
另外,您將調用放在類window.onload
內部;把它搬到外面去!
CSS 問題:
font: bold;
不起作用,你需要使用font-weight: bold;
另外,您忘記了選擇器中的句點Toggle_bold
。應該是.Toggle_bold
選擇班級。
這是包含最終固定代碼的 CodePen。
我希望這能解決您的問題!

TA貢獻2065條經驗 獲得超14個贊
由于您的代碼有很多問題,因此進行了一些編輯。容器 ID 有一個拼寫錯誤,該按鈕是使用 Button_container 創建的,它實際上是 ID 等。下面您可以看到按鈕是如何創建的。
創建元素:
在 createElement 中,我們必須指定標簽名稱而不是 ID 本身來創建新的 html 元素。
document.createElement('button');??//p?tag,?h1,h2,h3?tags?etc,?divs
設置屬性:
對于 id,我們使用setAttribute來設置指定元素上的屬性值。如果屬性已經存在,則更新值;否則,將添加具有指定名稱和值的新屬性。
btn.setAttribute("id",?"button_content");?//Ids,classes?and?data-attribute ??????????????????????????????????????????//id="myid",?class="myclass",?data-myid=1
內文:
最后對于值,我們使用innerText設置按鈕的文本并調用onLoad。
btn.innerText?="Click?me";
完整代碼:
<!DOCTYPE html>
<html>
<head>
? ? <title>Website Project</title>
? ? <link href="css/style.css" rel="stylesheet" type="text/css">
? ? <link rel="stylesheet" >
? ? <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
? ? <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
? ? <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
<style>
Toggle_bold {
? ? font: bold;
}
.Toggle_width{
? ? width: 50%;
}
.Toggle_width{
? ? color: #ff2800;
}
.Toggle_size{
? ? font-size: 100%;
}
#button_containter{
? ? display: flex;
? ? align-items: center;
? ? justify-content: center;
? ? text-align: center;
}
</style>
</head>
<body>
<div id ="button_container"></div>
<script>
function createButton (name){
? ? const btn = document.createElement('button'); //Add button with create Element
? ? btn.setAttribute("id", "button_content"); //Add Id with setAttribute method
? ? btn.innerText ="Click me";// Add value of the button with innerText property
? ? let container = document.getElementById("button_container"); //Fetch container div
? ? console.log(btn);
? ? console.log(container);
? ? container.appendChild(btn); //Append button to it.
}
function makeBold(){
// changing the size to bold, getting it from CSS s
? ? this.p.classList.toggle("Toggle_bold");
}
function changedWidth(){
? ? this.p.classList.toggle('Toggle_width');
}
function changeColor(){
? ? this.p.classList.toggle('Toggle_width');
}
function changeSize(){
? ? this.p.classList.toggle('Toggle_size');
}
window.onload = () => {
? ? createButton();// call button function here to create the button
}
</script>
</body>
</html>
最后,我相信我們通過實踐來學習,所以我希望這有助于消除一些困惑并解決您的問題:)。
- 1 回答
- 0 關注
- 129 瀏覽
添加回答
舉報