三元运算符不会更改backgroundColor

时间:2016-10-21 12:40:57

标签: javascript ternary-operator

我尝试在输入为空时设置背景,并在有一些

时保留此值
.modal-dialog.full-screen {
    position:fixed;
    //width:auto;  // uncomment to make the width based on the left/right attributes.
    margin:auto;                        
    left:0px;
    right:0px;
    top:0px;
    bottom:0px;
}

.modal-dialog.full-screen .modal-content {
      position:absolute;
      left:10px;
      right:10px;
      top:10px;
      bottom:10px;
}

.modal-dialog.full-screen .modal-content .modal-header {
        height:55px;  // adjust as needed.
}

.modal-dialog.full-screen .modal-content .modal-body {
        overflow-y: auto;
          position: absolute;
          top: 0;
          bottom: 0;
        left:0;
        right:0;
          margin-top: 55px; // .modal-header height
          margin-bottom: 80px;  // .modal-footer height
}

.modal-dialog.full-screen .modal-content .modal-footer {
        height:80px;  // adjust as needed.
        position:absolute;
        bottom:0;
        left:0;
        right:0;
}

1 个答案:

答案 0 :(得分:4)

你的作业只是在错误的地方:

function emptyto(element){
    return element.style.backgroundColor = element.value == '' ? "#ccc" : element.val();
    // ----^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
}

另外:DOM元素没有val方法。您要么在两个地方都使用value

function emptyto(element){
    return element.style.backgroundColor = element.value == '' ? "#ccc" : element.value;
    // ----^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
}

或者如果你正在使用jQuery,要包装元素并在两个地方使用val(以及css):

function emptyto(element){
    var $el = $(element);
    return $el.css("backgroundColor", $el.val() == '' ? "#ccc" : $el.val());
}

实际上,由于'' falsy 值,我们可以使用curiously-powerful || operator 1 来简化:

function emptyto(element){
    return element.style.backgroundColor = element.value || "#ccc";
}

1 (这是我贫血的小博客上的帖子。)