样式没出现在固定的div上

时间:2016-07-28 15:16:07

标签: javascript html

我有一个div想要出现在其他div之上,这是它的代码:

function displayMessage(content) {
        //content is a string
        var newElement = document.createElement('div');
        newElement.innerHTML = content;
        newElement.style.position = "fixed";
        newElement.style.left = "50%";
        newElement.style.right = "50%";
        newElement.style.top = "50%";
        newElement.style.bottom = "50%";
        newElement.style.backgroundColor = "#99ff33";
        newElement.style.border = "thick solid";
        newElement.style.display = "inline-block";
        newElement.style.zIndex = 100
}

当我这样做时,背景颜色不会出现,边框只是屏幕上的一个点。然而,当我评论出位置时,一切正常,但我的div位于屏幕的底部。

function displayMessage(content) {
        //content is a string
        var newElement = document.createElement('div');
        newElement.innerHTML = content;
        //newElement.style.position = "fixed";
        newElement.style.left = "50%";
        newElement.style.right = "50%";
        newElement.style.top = "50%";
        newElement.style.bottom = "50%";
        newElement.style.backgroundColor = "#99ff33";
        newElement.style.border = "thick solid";
        newElement.style.display = "inline-block";
        newElement.style.zIndex = 100
}

如何才能显示背景颜色和边框,并且仍然可以修复div的样式?

2 个答案:

答案 0 :(得分:0)

在底部添加:

document.getElementsByTagName('body')[0].appendChild(newElement);

赞这个

function displayMessage(content) {
    //content is a string
    var newElement = document.createElement('div');
    newElement.innerHTML = content;
    newElement.style.position = "fixed";
    newElement.style.left = "50%";
    newElement.style.right = "50%";
    newElement.style.top = "50%";
    newElement.style.bottom = "50%";
    newElement.style.backgroundColor = "#99ff33";
    newElement.style.border = "thick solid";
    newElement.style.display = "inline-block";
    newElement.style.zIndex = 100;
    document.getElementsByTagName('body')[0].appendChild(newElement);
}

答案 1 :(得分:0)

你已经设置了左边的'并且'对'属性为50%,这意味着您已迫使div的左边距离屏幕左侧(即屏幕中间)的屏幕宽度的50%,右侧相同。所以它不能超过0像素。

尝试使用略低于50%的值,或使用calc和设定宽度进行设置,例如:

final ActionBar myActionBar = getSupportActionBar();
if (myActionBar != null) {
    myActionBar.setTitle("This a new text");
}

这会将左侧位置固定为100px,小于屏幕宽度的50%。如果这是您想要的,那么结合200px宽度将使其居中。请注意,'权利'风格不再需要。然后对顶部和底部做同样的事情。