简体   繁体   中英

How can I give a javascript element a CSS class?

I've got the following code

var addressPopupMenu = window.createPopup();
function showAddressPopup() {
    var popup = document.getElementById('addressFullSpan');

    popupMenuBody = popupMenu.document.body;
    popupMenuBody.style.backgroundColor = "#336699";
    popupMenuBody.style.border = "solid 2px; white";
    popupMenuBody.style.fontSize="130%";
    popupMenuBody.style.color="white";
    popupMenuBody.style.padding="10px";
    popupMenuBody.style.paddingLeft="30px";

As you can see I'm repeating popupMenuBody.style . How can I give popupMenuBody.style a css class so I dont have to repeat this for every popup

edit: it's not working

I've added popupMenuBody.className = "popups";

.popups
    {
        background-color: #29527A;
        border: solid 2px; white;
        fontSize:120%;
        pcolor:white;
        padding:10px;
        paddingLeft:30px;
        textTransform:capitalize;
    }

also yes, i am including the .css in my page its working else where on the page

popupMenuBody.className = "class_name";

popupMenuBody.className = "my class";

.popups
    {
        background-color: #29527A;
        border: solid 2px white;
        font-size: 120%;
        color: white;
        padding: 10px;
        padding-left: 30px;
        text-transform: capitalize;
    }

use jquery addClass? http://api.jquery.com/addClass/

我会使用Jquery和addClass()来做到这一点:

$('#addressFullSpan').addClass('name')

jQuery has the method addClass() for applying a CSS class to an element

http://api.jquery.com/addClass/

Have you tried :

var addressPopupMenu = window.createPopup();
function showAddressPopup() {
    var popup = document.getElementById('addressFullSpan');
    popupMenuBody = popupMenu.document.body;
    popupMenuBody.className = "className";
    ...
}

To assign a CSS class to an element created in JavaScript, you can just use the following line of code:

popupMenuBody.className = "popups";

You've said that this doesn't work, but this is actually because your CSS is broken. I'm assuming that you've copy/pasted some JavaScript into your CSS file and changed it a bit, and as a result, your property names are all wrong. What you actually need for your CSS is this:

.popups
{
    background-color: #29527A;
    border: solid 2px white;
    font-size:120%;
    color:white;
    padding:10px;
    padding-left:30px;
    text-transform:capitalize;
}

Notice that I have:

  1. removed the ";" between "2px" and "white"
  2. renamed "fontSize" to "font-size"
  3. renamed "pcolor" to "color"
  4. renamed "paddingLeft" to "padding-left"

Your CSS should now get applied correctly.

为了避免覆盖popupMenuBody上的现有类名,请执行以下操作:

popupMenuBody.className += ' class_name';

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