<分区>
关闭 8 年前。
- 这个问题是由于打字错误或无法再重现的问题引起的。虽然类似的问题可能是on-topic在这里,这个问题的解决方式不太可能帮助 future 的读者。
- 编辑问题以包含 desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem .这将有助于其他人回答问题。
<分区>
关闭 8 年前。
我有一个 jQuery 函数的问题:.css()
这是我的 HTML 代码:
<div class="..." id="about">
// OTHER HTML CODE
</div>
这是我的 jQuery 代码:
(function($, window, document) {
$(function() {
var viewportHeight = $(window).height();
$('#about').css( "margin-top" , viewportHeight );
}(window.jQuery, window, document));
我已经尝试了所有可能的组合,但无论如何都行不通。我已经尝试了 .css() 方法的所有可能的合成器,但没有结果。 我还尝试在 .css() 函数中应用其他属性,在 DOM 准备好时将其他方法应用于 $('#about') 对象作为 .click 或 .fadeOut(),但没有结果。
我的环境是一个使用 Yeomann、Grunt 和 Angular.js 构建的元素。我担心 Angular 会干扰我正在构建的功能,但对我来说这似乎很奇怪,因为其他 HTML 元素上的 .click() 方法正在工作(例如,我能够 .addClass() 到元素)。
有人知道这个问题吗?
最佳答案
至于注释,jquery 很可能无法获取元素,因为该元素在特定时刻不存在。
你应该多用 Angular 特性,少用 Jquery 东西。 无论如何,可以使用 ng-init 找到一种解决方案
<div ng-controller="AboutController">
<div class="..." id="about" ng-init="measure()">
// OTHER HTML CODE
</div>
</div>
然后在 AboutController
或任何包装您的 about
元素的 Controller 中,您可以使用您喜欢的任何代码,我将使用纯 JS 版本
(function () {
'use strict';
angular
.module('app') //whatever module you're using
.controller('AboutController', tcController);
tcController.$inject = ['$scope', '$window'];
/* @ngInject */
function tcController($scope, $window) {
$scope.measure = function() {
var viewportHeight = $window.height();
document.querySelector('#about').style.marginTop = viewportHeight + 'px';
}
}
})();
关于javascript - .css() 函数不会为任何元素设置任何属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29894158/