根据浏览器宽度更改边距Javascript

时间:2017-03-02 17:48:17

标签: javascript

我正试图制作一个"附加评论"我的网站上的框,浮动到页面右侧,而右边有4个输入。

出于某种原因,浏览器调整大小的评论框位于输入后面。

我想这样做,以便当浏览器小于(例如400px)时,它会在评论框中应用边距。我试过下面的内容,但这似乎没有用。

var browserSize = window.innerWidth();
    var additional = document.getElementById("additional");

    if(browserSize < 400px) {
        additional.style.marginTop = "200px";
    }

有人可以指导我去哪儿吗? 非常感谢提前!

2 个答案:

答案 0 :(得分:3)

为什么不使用CSS媒体查询?你可以在样式表中做这样的事情:

class MyCell: UITableViewCell {
    // Create `@IBOutlet weak var ...` for all of the controls in your cell here
    @IBOutlet weak var cellNumber: UILabel!

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.configureCell()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.configureCell()
    }

    func configureCell() {
        // Your stuff to load up the IBOutlet controls of your cell with defaults.
        // You will be able to override these when the instantiated cell is passed to
        // `tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell` 
        // in the `UITableViewDataSource`
    }
}

但是,您应尽量避免将ID用作CSS选择器。

答案 1 :(得分:1)

为浏览器调整大小添加一个事件监听器,并为其中的工作添加一个函数:

function processResize()
{
var browserSize = window.innerWidth();
    var additional = document.getElementById("additional");

    if(browserSize < 400px) {
        additional.style.marginTop = "200px";
    }
}
window.addEventListener("resize", processResize);
相关问题