2016-12-28 15 views
1

我的網頁採取CSS屬性從用戶包括以下內容:如何使用的js

  1. 輸入型文本
  2. 按鈕

我想用戶輸入的CSS代碼在輸入字段中,然後當他點擊按鈕時,代碼必須應用到段落中。

示例: 用戶在輸入處輸入了color:red。 他點擊了按鈕。 他輸入的代碼(顏色:紅色)應該在段落

應用我做了這段代碼來做到這一點,但它有一個問題,我認爲這是關於連接所以代碼。有人可以幫助我嗎?

這裏是我的代碼 - JS行數10

var Inpt = document.getElementById("Inpt"), 
 
    Par = document.getElementById("Par"), 
 
    Btn = document.getElementById("Btn"), 
 
    Val; 
 

 
Btn.onclick = function() { 
 
    "use strict"; 
 
    Val = Inpt.value; 
 
    Val = Val.split(":"); 
 
    Par.style.Val[0] = Val[1]; 
 
};
<input type="text" id="Inpt"> 
 
<button id="Btn"> Apply</button> 
 
<p id="Par">This Is The Paragraph</p>

+0

'Par.style [瓦爾[0]' –

回答

1

這裏有我的回答,我改變一點點的名字變量,但它的作品像魅力:

HTML:

<input type="text" id="Inpt"> 
<button id="Btn"> Apply</button> 
<p id="Par">This Is The Paragraph</p> 

的Javascript:

var input = document.getElementById("Inpt"), 
    parameter = document.getElementById("Par"), 
    button = document.getElementById("Btn"), 
    value; 

button.onclick = function() { 
    "use strict"; 
    value = input.value; 
    value = value.split(":"); 
    parameter.style[value[0]] = value[1]; 
}; 

的jsfiddle鏈接:https://jsfiddle.net/wj8o4uq8/

希望它能幫助!

+0

謝謝你,我試了一下,但我一直在控制檯中看到這個錯誤:意外的令牌[ –

+0

我解決了一個小錯字,仍然使用Btn而不是按鈕。另外我加了一個jsfiddle的鏈接來檢查它是否正常工作。您能否再次與我們分享控制檯中顯示的完整錯誤?謝謝。 – avilac

+0

非常感謝bro,現在效果很好:D –

0

var Inpt = document.getElementById("Inpt"), 
 
    Par = document.getElementById("Par"), 
 
    Btn = document.getElementById("Btn"), 
 
    Val; 
 

 
Btn.onclick = function() { 
 
    "use strict"; 
 
    Val = Inpt.value; 
 
    Par.style.cssText = Val; 
 
};
<input type="text" id="Inpt"> 
 
<button id="Btn"> Apply</button> 
 
<p id="Par">This Is The Paragraph</p>

1

嘗試輸入此值:如果您想多種樣式color:red;

color:red;font-size:20px;

var Inpt = document.getElementById("Inpt"), 
 
    Par = document.getElementById("Par"), 
 
    Btn = document.getElementById("Btn"), 
 
    Val; 
 

 
Btn.onclick = function() { 
 
    "use strict"; 
 
    Val = Inpt.value; 
 
    Par.setAttribute("style", Val); 
 
};
<input type="text" id="Inpt"> 
 
<button id="Btn"> Apply</button> 
 
<p id="Par">This Is The Paragraph</p>