我有以下
<!doctype html>
<html>
<head>
<script src='../bower_components/webcomponentsjs/webcomponents-lite.js'></script>
<link rel="import" href="../bower_components/paper-dropdown-menu/paper-dropdown-menu.html">
<link rel="import" href="../bower_components/paper-item/paper-item.html">
<link rel="import" href="../bower_components/paper-listbox/paper-listbox.html">
</head>
<body unresolved>
<dom-module id='base-page'>
<template>
<paper-dropdown-menu>
<paper-listbox class='dropdown-content' selected='0'>
<paper-item>This is a very long text that I have in my paper drop down</paper-item>
</paper-listbox>
</paper-dropdown-menu>
</template>
</dom-module>
<script>
HTMLImports.whenReady(function() {Polymer({
is: 'base-page',
properties: {
}
});});
</script>
<base-page></base-page>
</body>
所选文字是&#34;这是我在论文中删除的一段非常长的文本&#34;,但它被切断了。有没有办法让纸张下拉菜单自动调整宽度?
在这里放置一些东西:http://jsbin.com/dejukufaqe/edit?html,output
干杯
答案 0 :(得分:2)
要完成此操作,您必须计算给定字体中paper-list
中每个字符串的像素宽度,获取宽度的最大值,并将paper-dropdown-menu
的宽度设置为那个价值。
请参阅下面的演示。宽度仅限于容器的宽度,因此不会从页面上展开。
<head>
<meta charset="utf-8">
<base href="https://cdn.rawgit.com/download/polymer-cdn/1.8.0/lib/">
<link rel="import" href="polymer/polymer.html">
<script src="webcomponentsjs/webcomponents-lite.js"></script>
<link rel="import" href="paper-dropdown-menu/paper-dropdown-menu.html">
<link rel="import" href="paper-item/paper-item.html">
<link rel="import" href="paper-listbox/paper-listbox.html">
</head>
<body>
<base-page></base-page>
<dom-module id='base-page'>
<style>
paper-dropdown-menu {
max-width: 100%;
}
</style>
<template>
<paper-dropdown-menu id="menu">
<paper-listbox id="list" class='dropdown-content' selected='0'>
<paper-item>Foo</paper-item>
<paper-item>Bar</paper-item>
<paper-item>This is a very very long long text that I have in my paper drop down</paper-item>
<paper-item>Baz</paper-item>
</paper-listbox>
</paper-dropdown-menu>
</template>
<script>
Polymer({
is: 'base-page',
ready: function() {
this.$.menu.style.width = this.maxTextWidth() + 'px';
},
maxTextWidth: function() {
var font = 'normal 13pt Roboto,Arial';
var widths = this.$.list.items.map(function(item) {
var text = item.textContent && item.textContent.trim();
return text ? getTextWidth(text, font) : 0;
});
return Math.max.apply(Math, widths);
}
});
// http://stackoverflow.com/questions/118241/calculate-text-width-with-javascript/21015393#21015393
function getTextWidth(text, font) {
// if given, use cached canvas for better performance
// else, create new canvas
var canvas = getTextWidth.canvas || (getTextWidth.canvas = document.createElement("canvas"));
var context = canvas.getContext("2d");
context.font = font;
var metrics = context.measureText(text);
return metrics.width;
}
</script>
</dom-module>
</body>