简体   繁体   中英

How do you insert multiple lines to a webpage using the span element?

I'm working on a game that uses a map (of course, this is multiple lines). I was wondering if you can make the span tag cover multiple lines (with the end of the row being a new line).

Example map:
- - O
- XO
O - O

Is there any way to get the map to appear exactly how it is above in the webpage?

Here is some code from the JS file:

for (var col = 0; col < mapHeight; col++)
{
    for (var row = 0; row < mapWidth; row++)
    {
        var character = map2[col][row];

        if (character == "X" || character == "O")
        {
            alertMessage += " " + character;
        }
        else
        {
            alertMessage += "  " + character;
        }

        document.getElementById("map").innerHTML += character;
    }
    alertMessage += "\n";
    // document.getElementById("map").innerHTML += "\n";
}

The last line that is commented out is what I want to do, but it won't work with a simple "\\n"

In your javascript you may have

var map = "- - O\\n- XO\\nO - O";

Maybe this will come from the server.

You can add lines by doing a

map = map.replace(/\n/g, "<br/>"); 

to add the lines

Use the <br> tag which signifies a line break

 <span>--o<br>-xo<br>oo</span> 

or the <pre> tag which signifies pre-formatted text

 <pre>--o -xo oo</pre> 

or the <div> tag which signifies a division of the vertical page flow.

 <div>--o</div> <div>-xo</div> <div>oo</div> 

You probably want a pre . These preserve whitespace and are generally displayed in a monospace font.

1. use <pre>

2. use <br />

3. Every line in <div></div> Example:

<div><span>-</span><span>-</span><span>o</span></div>
<div><span>-</span><span>x</span><span>o</span></div>
<div><span>o</span><span>-</span><span>o</span></div>

You can use the <br> tag within the <span> tag.

<span>
    - - O<br>
    - X O<br>
    O - O
</span>

Here is a jsfiddle to take a look: https://jsfiddle.net/8gtv3wdL/

I figured it out! Thanks everyone for your help!

I did it with this:
document.getElementById("map").innerHTML += "< br />";

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