简体   繁体   中英

How to change all of a div's style attribute using JavaScript?

I'm working on my own in browser live HTML/CSS code editor. What I'm having trouble with is applying the css styles typed out by the user to my div preview pane.

What I currently have is

   <html lang="en">
<head>
<meta charset="utf-8">
    <title>Code Editor</title>
    <style>
        .wrapper{
            width: 100%;
        }
        .textWrapper {
            width: 30%;
            height: 100%;
            float: left;
        }
        #css{
            height: 300px;
            width: 100%;            
        }
        #html {
            height: 300px;
            width: 100%;
        }
        #preview {
            height:600px;
            width: 400px;
            float:left;
            border:2px solid black;
            margin: 20px;
        }


    </style>

</head>
    <body>
    <div class ="wrapper">
        <div class ="textWrapper">
        <textarea placeholder="CSS..." id="css"></textarea>
        <textarea placeholder="HTML..." id="html"></textarea>
        </div>
        <div id="preview"></div>
        <button onclick="launch()">Launch</button>
        <button onclick="toggleCSS()">Toggle</button>
        <button onclick="clear()">Clear</button>

        <script src="bebk9hScripts.js"></script>
    </div> 
    </body>
</html>

and for my script page

function launch() { 
    document.getElementById("preview").innerHTML = document.getElementById("html").value;
} 


function toggleCSS() {

    document.getElementById("preview").style = document.getElementById("css").value;
}

but that is not working. Any suggestions? Also I realize using an iframe would be easier but we aren't supposed to.

A simple and effective way to accomplish what you're trying to do is to set the innerHTML of your preview element. This does not prevent you from utilizing HTML, CSS, or JavaScript in any way, so long as all necessary dependencies have been accounted for prior to your preview element. The simple implementation is:

  var preview = document.getElementById("preview");
  var html = document.getElementById("html").value;
  var css = document.getElementById("css").value;

  preview.innerHTML = html;
  preview.innerHTML += '<style>' + css + '</style>';

However, as a developer in a very rapid environment, I can honestly say, using an interval to refresh the preview is much appreciated when you're trying to quickly update things. It'll be up to you as to how fast of an interval you'll use to refresh, or you could give your users a setting for update intervals.

Keep in mind though, that using intervals can cause undesired behavior such as animations being cutoff, etc. This is why a lot of code editors online use a refresh or run button in the first place. But I'd like to point out the usefulness of utilizing the keyup event that is available to us.

Coupling the keyup event with a timer, a manual refresh button, and an interval would be my recommendation:

 var html = document.getElementById("html"); var css = document.getElementById("css"); // Use the `keyup` event as a primary check for updates. var keyDelay = 1000; var keyRecieved = false; var timeSinceLastKeyRecievedInMilliseconds = 0; document.addEventListener('keyup', prepareForRefresh); function prepareForRefresh() { keyRecieved = true; timeSinceLastKeyRecievedInMilliseconds = 0; } function update() { var preview = document.getElementById("preview"); preview.innerHTML = html.value; preview.innerHTML += '<style>' + css.value + '</style>'; } // Use an interval for checking if we should update. setInterval(function() { if (keyRecieved) { timeSinceLastKeyRecievedInMilliseconds += 100; if (timeSinceLastKeyRecievedInMilliseconds >= keyDelay) { timeSinceLastKeyRecievedInMilliseconds = 0; keyRecieved = false; update(); } } }, 100); // Use a high interval as a fail-safe for flukes. var interval = 180000; setInterval(update, interval);
 input[type=text] { margin: 5px; background-color: #fffa; border: 2px solid transparent; border-bottom: 2px solid #fff; border-radius: 5px; }.update { width: 20%; padding: 10px; margin: 5px; background-color: #f33a; cursor: pointer; user-select: none; }.primary-content { display: flex; align-items: center; justify-content: center; flex-direction: column; } html, body { overflow-y: auto; }
 <link href="https://s3-us-west-2.amazonaws.com/s.cdpn.io/2940219/PerpetualJ.css" rel="stylesheet"/> <div id="primary-content" class="primary-content"> <input id="html" type="text" placeholder="HTML" /> <input id="css" type="text" placeholder="CSS" /> <div class="update" onclick="update();">Refresh</div> <div id="preview"></div> <div id="refresh-preview"></div> </div>

The simple example above utilizes a combination of the keyup event, a timer for detecting how long it's been since the user provided input, and a high interval as a fail-safe. This is close to the method utilized by CodePen, and I heavily recommend it for a web focused editor. Feel free to check out my implementation of this in it's simplest form over on CodePen .

Your Code works!

EDIT : Well, at least kind of. It applies the styles directly only to the preview element, not its children (see comments below this post).


Below ist my old answer:

There is nothing wrong with it, and the issue must be somewhere else.
Possible issues that come to mind are:

  • The CSS entered by the user is not valid, or is overwritten by another stylesheet
  • The Javascript function to update the file does not get triggered
  • The elements referenced in the Javascript are the wrong ones

Here is minimal working example using your code:

 function toggleCSS() { document.getElementById("preview").style = document.getElementById("css").value; } document.getElementById("apply_css").onclick = toggleCSS;
 <textarea id="css" cols="40" rows="5"> width: 150px; height: 100px; border: 1px solid green; background: rgb(170, 200, 250); </textarea> <br> <button id="apply_css">Apply CSS!</button> <br> <div id="preview"></div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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