javascript 如何使用淘汰赛使窗口大小可观察
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10854179/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make window size observable using knockout
提问by Dean
Trying to do something about the browser window:
尝试对浏览器窗口做一些事情:
- Is it possible to make the window size (
$(window).width(), $(window).height()
) observable using Knockout? - How to keep FUTURE Added Elementsin the center of the window? Is there something can be done using the jquery live methodor the knockout custom bindings?
- 是否可以
$(window).width(), $(window).height()
使用 Knockout使窗口大小 ( ) 可见? - 如何将未来添加的元素保持在窗口的中央?有什么可以使用jquery live 方法或淘汰赛自定义绑定来完成的吗?
Any Suggestion appreciated!
任何建议表示赞赏!
回答by madcapnmckay
The only way to make them observable is to proxy them into observable properties.
使它们可观察的唯一方法是将它们代理为可观察的属性。
var yourViewModel = {
width: ko.observable(),
height: ko.observable()
};
var $window = $(window);
$window.resize(function () {
yourViewModel.width($window.width());
yourViewModel.height($window.height());
});
I don't really understand your second question. Couldn't you just use css for this?
我不太明白你的第二个问题。你不能只使用 css 吗?
EDIT
编辑
Second question. One possibility would be write a binding handler to do this (untested).
第二个问题。一种可能性是编写一个绑定处理程序来执行此操作(未经测试)。
ko.bindingHandlers.center {
init: function (element) {
var $el = $(element);
$el.css({
left: "50%",
position: "absolute",
marginLeft: ($el.width() / 2) + 'px'
});
}
}
The 50% and margin-left is a great way to center things in your scenarios since it automatcially works even if the window is resized. Obviously if the divs themselves resize you need to recalculate the left margin, this could always be bound to a value on the viewmodel. Hope this helps.
50% 和 margin-left 是在您的场景中居中的好方法,因为即使调整窗口大小,它也会自动工作。显然,如果 div 本身调整大小,您需要重新计算左边距,这始终可以绑定到视图模型上的值。希望这可以帮助。
回答by Ray
To elaborate on Dean's comment of his winsize
custom bindingHandler, this is how it can be used:
要详细说明 Dean 对其winsize
自定义 bindingHandler的评论,可以使用以下方法:
JS
JS
ko.bindingHandlers.winsize = {
init: function (element, valueAccessor) {
$(window).resize(function () {
var value = valueAccessor();
value({ width: $(window).width(), height: $(window).height() });
});
}
}
self.windowSize = ko.observable();
HTML
HTML
<div data-bind="winsize: windowSize"></div>