我在组件上的数据中有一个listBoxStyle。我已将其绑定到列表框。样式之一是position: absolute
。我需要将框放置在输入元素的正下方。在安装的挂钩中,我要从输入元素获取顶部,左侧和高度,并修改listBoxStyle。不幸的是,这根本不起作用。列表框将保留在其最初创建的位置。
我真的在寻找一种将列表框动态移动到所需位置的方法。
代码如下:
Vue.component("employee-search", {
props: ["small"],
data: function () {
return {
searchText: "",
isSmall: (this.small ? true : false),
list: [],
formControlCss: "form-control",
fullWidthCss: "full-width",
smCss: "input-sm",
listBoxStyle: {
position: "absolute",
top: 0,
left: 0,
backgroundColor: "white",
borderStyle: "solid",
borderWidth: "1px",
padding: "5px 25px 5px 0px",
borderColor: "#245580"
}
}
},
template:
'<div>' +
' <input ref="inputBox"' +
' v-model="searchText" ' +
' v-on:input="handleInputChange"' +
' v-bind:class="[formControlCss, fullWidthCss, isSmall ? smCss : \'\']" ' +
' placeholder="Search on name or badge #..." > ' +
' <div ref="listBox" v-bind:style="listBoxStyle">' +
' <ul v-show="list.length > 0" style="margin-top: 10px"> ' +
' <li ' +
' v-for="item in list" ' +
' v-on:click="handleSelect(item)" ' +
' style="cursor: pointer; margin-bottom: 5px;">' +
' {{ item.label }}' +
' </li>' +
' </ul>' +
' </div>' +
'</div>',
methods: {
handleInputChange: function () {
console.log("handleInputChange: " + this.searchText);
var self = this;
if (this.searchText.length > 2) {
$.ajax({
url: "/api/badges?filter=" + this.searchText,
dataType: "json",
type: "GET",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
console.log(data);
self.emptyList();
data.forEach(function (item) {
self.list.push(JSON.parse(item));
});
self.positionListBox();
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
} else {
this.emptyList();
}
},
handleSelect: function (item) {
console.log(item);
this.searchText = item.label;
this.emptyList();
this.$emit("selected", item);
},
emptyList: function () {
var count = this.list.length;
for (var x = 1; x <= count; x++) {
this.list.shift();
}
},
positionListBox: function () {
}
},
mounted: function () {
console.log("EmpSearch: ", this.$refs.listBox);
this.listBoxStyle.top = this.$refs.inputBox.getBoundingClientRect().top + this.$refs.inputBox.getBoundingClientRect().height;
this.listBoxStyle.left = this.$refs.inputBox.getBoundingClientRect().left;
}
});
答案 0 :(得分:2)
更改listBoxStyle.top
和listBoxStyle.left
时,必须声明其单位。否则,它们会被视为损坏的CSS属性
mounted: function () {
console.log("EmpSearch: ", this.$refs.listBox);
this.listBoxStyle.top = this.$refs.inputBox.getBoundingClientRect().top + this.$refs.inputBox.getBoundingClientRect().height + 'px';
this.listBoxStyle.left = this.$refs.inputBox.getBoundingClientRect().left + 'px';
}