简体   繁体   中英

javascript style on click event

I am trying to do a game menu on javascript, I'm generating HTML with javascript because of practice.

I got this event listener that I should click to obtain the lhyperlink to another page, but when it appears, the hyperlink instead of getting centered by CSS stylesheet, it goes default and gets to the left.

I don't know how it's called in CSS

Here's my code:

const h1 = document.createElement("h1");
const parr1 = document.createElement("p");
const parr2 = document.createElement("p");
body.appendChild(h1);
body.appendChild(parr1);
body.appendChild(parr2);
h1.innerHTML = "Aventura D&D";
parr1.innerHTML = "Empezar Juego";
parr2.innerHTML = "Cargar juego";

parr1.addEventListener('click', (event) => {
    let a = document.createElement('a');
    let link = document.createTextNode('Juego Nuevo');
    a.appendChild(link);
    a.title = "Juego Nuevo";
    a.href = '/game1.html';
    //Here is the problem!!!!
    document.body.replaceChild(a, parr1);
});

I went to the Element Inspector and I was able to modify the element by modifying the body tag. Why?

Here is the CSS sheet

body{

    background: black;
    color: goldenrod;
    //This is the part that is working but I wonder why if the spawned                                                                                                                                  //hyperlink should obey <a> tag
    text-align: center;
}

h1{
    font-size: 9em;
    font-family: 'Courier New', Courier, monospace;
    color: #c90000;
    text-align: center;
}

p{
    font-size: 3em;
    text-align: center;
}

a{
    font-size: 3em;
}
  1. I would change from where it says document.body.replaceChild(a, parr1); to say document.body.replaceChild(a, this); . There may be an issue with referencing.

  2. For the text alight, try using a.style.textAlign = "center"; rather than a.styles.cssText('align-text: "center;')

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