Javascript 自动将 jQuery UI 对话框的大小调整为 ajax 加载的内容的宽度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2231446/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 23:22:00  来源:igfitidea点击:

Automatically resize jQuery UI dialog to the width of the content loaded by ajax

javascriptjqueryajaxjquery-uijquery-ui-dialog

提问by womp

I'm having a lot of trouble finding specific information and examples on this. I've got a number of jQuery UI dialogs in my application attached to divs that are loaded with .ajax() calls. They all use the same setup call:

我很难找到有关此的具体信息和示例。我的应用程序中有许多 jQuery UI 对话框附加到加载了 .ajax() 调用的 div。它们都使用相同的设置调用:

 $(".mydialog").dialog({
        autoOpen: false,
        resizable: false,
        modal: true
 });

I just want to have the dialog resize to the width of the content that gets loaded. Right now, the width just stays at 300px (the default) and I get a horizontal scrollbar.

我只想将对话框的大小调整为加载的内容的宽度。现在,宽度只是保持在 300px(默认值),我得到了一个水平滚动条。

As far as I can tell, "autoResize" is no longer an option for dialogs, and nothing happens when I specify it.

据我所知,“autoResize”不再是对话框的一个选项,当我指定它时没有任何反应。

I'm trying to not write a separate function for each dialog, so .dialog("option", "width", "500")is not really an option, as each dialog is going to have a different width.

我试图不为每个对话框编写一个单独的函数,所以.dialog("option", "width", "500")不是一个真正的选项,因为每个对话框都有不同的宽度。

Specifying width: 'auto'for the dialog options just makes the dialogs take up 100% of the width of the browser window.

指定width: 'auto'对话框选项只会使对话框占据浏览器窗口宽度的 100%。

What are my options? I'm using jQuery 1.4.1 with jQuery UI 1.8rc1. It seems like this should be something that is really easy.

我有哪些选择?我使用 jQuery 1.4.1 和 jQuery UI 1.8rc1。看起来这应该是一件很容易的事情。

EDIT: I've implemented a kludgy workaround for this, but I'm still looking for a better solution.

编辑:我已经为此实施了一个笨拙的解决方法,但我仍在寻找更好的解决方案。

回答by Fermin

I've just wrote a tiny sample app using JQuery 1.4.1 and UI 1.8rc1. All I did was specify the constructor as:

我刚刚使用 JQuery 1.4.1 和 UI 1.8rc1 编写了一个很小的示例应用程序。我所做的只是将构造函数指定为:

var theDialog = $(".mydialog").dialog({
        autoOpen: false,
        resizable: false,
        modal: true,
        width:'auto'
});

I know you said that this makes it take up 100% width of the browser window but it works sweet here, tested in FF3.6, Chrome and IE8.

我知道你说过这使它占据了浏览器窗口的 100% 宽度,但它在这里工作得很好,在 FF3.6、Chrome 和 IE8 中进行了测试。

I'm not making AJAX calls, just manually changing the HTML of the dialog but don't think that will cause any probs. Could some other css setting be knocking this out?

我没有进行 AJAX 调用,只是手动更改对话框的 HTML,但不要认为这会导致任何问题。其他一些css设置可以解决这个问题吗?

The only problem with this is that it makes the width off-centre but I found this support ticketwhere they supply a workaround of placing the dialog('open')statement in a setTimeout to fix the problem.

唯一的问题是它使宽度偏离中心,但我发现了这个支持票,他们提供了一种将dialog('open')语句放入 setTimeout 以解决问题的解决方法。

Here is the contents of my head tag:

这是我的 head 标签的内容:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
<script type="text/javascript" src="jquery-ui.min.js"></script>
<link href="jquery-ui.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
    $(function(){
        var theDialog = $(".mydialog").dialog({
            autoOpen: false,
            resizable: false,
            modal: true,
            width: 'auto'
        });

        $('#one').click(function(){
            theDialog.html('some random text').dialog('open');
        });

        $('#two').click(function(){
            theDialog.html('<ul><li>Apple</li><li>Orange</li><li>Banana</li><li>Strawberry</li><li>long text string to see if width changes</li></ul>').dialog('open');
        });

        $('#three').click(function(){
            //this is only call where off-centre is noticeable so use setTimeout
            theDialog.html('<img src="./random.gif" width="500px" height="500px" />');
            setTimeout(function(){ theDialog.dialog('open') }, 100);;
        });
     });
</script>

I downloaded the js and css for Jquery UI from http://jquery-ui.googlecode.com/files/jquery-ui-1.8rc1.zip. and the body:

我从http://jquery-ui.googlecode.com/files/jquery-ui-1.8rc1.zip下载了 Jquery UI 的 js 和 css 。和身体:

<div class='mydialog'></div>
<a href='#' id='one'>test1</a>
<a href='#' id='two'>test2</a>
<a href='#' id='three'>test3</a>

回答by Fortes

Had the same problem and thanks to you mentioning that the real problem was related to CSS I found the issue:

有同样的问题,感谢你提到真正的问题与 CSS 相关,我发现了这个问题:

Having position:relativeinstead of position:absolutein your .ui-dialogCSS rule makes the dialog and width:'auto'behave strangely.

拥有position:relative而不是position:absolute在你的.ui-dialogCSS规则,使对话和width:'auto'行为怪异。

.ui-dialog { position: absolute;}

回答by Jason

Here's how I did it:

这是我如何做到的:

Responsive jQuery UI Dialog ( and a fix for maxWidth bug )

响应式 jQuery UI 对话框(以及对 maxWidth 错误的修复)

Fixing the maxWidth & width: auto bug.

修复 maxWidth & width: auto 错误。

回答by Salman A

You can avoid the 100% width issue by specifying a maximum width. The maxWidthoption does not seem to work; so set the CSS max-widthproperty on the dialog widget instead.

您可以通过指定最大宽度来避免 100% 宽度问题。该maxWidth选项似乎不起作用;因此max-width,请在对话框小部件上设置 CSS属性。

In case you also want to constrain the maximum height, use the maxHeightoption. It will correctly show a scrollbar when necessary.

如果您还想限制最大高度,请使用该maxHeight选项。必要时它将正确显示滚动条。

$(function() {
  var $dialog = $("#dialog");
  $dialog.dialog({
    autoOpen: false,
    modal: true,
    width: "auto"
  });
  /*
   * max-width should be set on dialog widget because maxWidth option has known issues
   * max-height should be set using maxHeight option
   */
  $dialog.dialog("widget").css("max-width", $(window).width() - 100);
  $dialog.dialog("option", "maxHeight", $(window).height() - 100);
  $(".test-link").on("click", function(e) {
    e.preventDefault();
    $dialog.html($(this.hash).html());
    // if you change the content of dialog after it is created then reset the left
    // coordinate otherwise content only grows up to the right edge of screen
    $dialog.dialog("widget").css({ left: 0 });
    $dialog.dialog("open");
  });
});
@import url("https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.min.css");
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>

<div id="dialog"></div>

<!-- test links -->

<p>
  <a href="#content-1" class="test-link">Image (Landscape)</a>
  <a href="#content-2" class="test-link">Image (Portrait)</a>
  <a href="#content-3" class="test-link">Text Content (Small)</a>
  <a href="#content-4" class="test-link">Text Content (Large)</a>
</p>
<p>If you are viewing in Stack Snippets > Full page then reload the snippet so that window height is recalculated (Right click > Reload frame).</p>

<!-- sample content -->

<div id="content-1" style="display: none;">
  <img src="https://i.stack.imgur.com/5leq2.jpg" width="450" height="300">
</div>

<div id="content-2" style="display: none;">
  <img src="https://i.stack.imgur.com/9pVkn.jpg" width="300" height="400">
</div>

<div id="content-3" style="display: none;">
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam sodales eu urna sit amet fermentum. Morbi ornare, leo ut ornare volutpat, nibh diam mattis elit, eget porta sapien quam eu mi. Nullam sollicitudin, nibh non suscipit commodo, nisi metus bibendum urna, vitae congue nisl risus eu tellus. Praesent diam ligula, hendrerit eget bibendum quis, convallis eu erat. Aliquam scelerisque turpis augue, sit amet dictum urna hendrerit id. Vestibulum luctus dolor quis ex sodales, nec aliquet lacus elementum. Mauris sollicitudin dictum augue eget posuere. Suspendisse diam elit, scelerisque eu quam vel, tempus sodales metus. Morbi et vehicula elit. In sit amet bibendum mi.</p>
</div>

<div id="content-4" style="display: none;">
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam sodales eu urna sit amet fermentum. Morbi ornare, leo ut ornare volutpat, nibh diam mattis elit, eget porta sapien quam eu mi. Nullam sollicitudin, nibh non suscipit commodo, nisi metus bibendum urna, vitae congue nisl risus eu tellus. Praesent diam ligula, hendrerit eget bibendum quis, convallis eu erat. Aliquam scelerisque turpis augue, sit amet dictum urna hendrerit id. Vestibulum luctus dolor quis ex sodales, nec aliquet lacus elementum. Mauris sollicitudin dictum augue eget posuere. Suspendisse diam elit, scelerisque eu quam vel, tempus sodales metus. Morbi et vehicula elit. In sit amet bibendum mi.</p>
  <p>Aenean eu magna tempor, pellentesque arcu eget, mattis enim. Cras at volutpat mi. Aenean id placerat felis, quis imperdiet nunc. Aenean a iaculis est, quis lacinia nisl. Sed aliquet sem eget justo convallis congue. Quisque rhoncus nulla sit amet cursus maximus. Phasellus nec auctor urna. Nam mattis felis et diam finibus consectetur. Etiam finibus dignissim vestibulum. In eu urna mattis dui pharetra iaculis. Nam eleifend odio et massa imperdiet, et hendrerit mauris tempor. Quisque sapien lorem, dapibus ut ultricies ut, hendrerit in nulla. Nunc lobortis mi libero, nec tincidunt lacus pretium at. Aliquam erat volutpat.</p>
  <p>Fusce eleifend enim nec massa porttitor tempor a eget neque. Quisque vel augue ac urna posuere iaculis. Morbi pharetra augue ac interdum pulvinar. Duis vel posuere risus. Interdum et malesuada fames ac ante ipsum primis in faucibus. Ut vitae lectus non nisl iaculis volutpat nec vitae ante. Maecenas quis condimentum elit. Sed nisl urna, convallis ut pellentesque sit amet, pellentesque eget quam. Pellentesque ornare sapien ac scelerisque pretium. Pellentesque metus tortor, accumsan in vehicula iaculis, efficitur eget nisi. Donec tincidunt, felis vel viverra convallis, lectus lectus elementum magna, faucibus viverra risus nulla in dolor.</p>
  <p>Duis tristique sapien ut commodo laoreet. In vel sapien dui. Vestibulum non bibendum erat. Etiam iaculis vehicula accumsan. Phasellus finibus, elit et molestie luctus, massa arcu tempor nulla, id hendrerit metus mauris non mi. Morbi a ultricies magna. Proin condimentum suscipit urna eu maximus. Mauris condimentum massa ac egestas fermentum. Praesent faucibus a neque a molestie. Integer sed diam at eros accumsan convallis.</p>
</div>

回答by Alex

For some reason I kept having this full page width problem with IE7 so I made this hack:

出于某种原因,我一直在使用 IE7 遇到这个全页宽度问题,所以我做了这个黑客:

var tag = $("<div></div>");
//IE7 workaround
var w;
if (navigator.appVersion.indexOf("MSIE 7.") != -1)
    w = 400;
else
    w = "auto";

tag.html('My message').dialog({
    width: w,
    maxWidth: 600,
    ...

回答by wheresrhys

I imagine setting float:left for the dialog will work. Presumably the dialog is absolutely positioned by the plugin, in which case its position will be determined by this, but the side-effect of float - making elements only as wide as they need to be to hold content - will still take effect.

我想为对话框设置 float:left 会起作用。大概对话框是由插件绝对定位的,在这种情况下,它的位置将由此确定,但是浮动的副作用 - 使元素的宽度仅与容纳内容所需的一样宽 - 仍然会生效。

This should work if you just put a rule like

如果你只是放置一个规则,这应该有效

.myDialog {float:left}

in your stylesheet, though you may need to set it using jQuery

在您的样式表中,尽管您可能需要使用 jQuery 设置它

回答by Jesús Alonso

I had the same problem when I upgraded jquery UI to 1.8.1 without upgrading the corresponding theme. Only is needed to upgrade the theme too and "auto" works again.

我在没有升级相应主题的情况下将jquery UI升级到1.8.1时遇到了同样的问题。只需要升级主题,“自动”再次工作。

回答by tsi

I had a similar problem.

我有一个类似的问题。

Setting widthto "auto"worked fine for me but when the dialog contained a lot of text it made it span the full width of the page, ignoring the maxWidthsetting.

设置width"auto"工作对我很好,但是当对话框中包含大量的文字它使人们跨越页的整个宽度,忽略了maxWidth设置。

Setting maxWidthon createworks fine though:

设置maxWidthcreate工作正常,但:

$( ".selector" ).dialog({
  width: "auto",
  // maxWidth: 660, // This won't work
  create: function( event, ui ) {
    // Set maxWidth
    $(this).css("maxWidth", "660px");
  }
});

回答by Ken Q

I had this problem as well.

我也有这个问题。

I got it working with this:

我得到了它的工作:

.ui-dialog{
    display:inline-block;
}

回答by taggartJ

All you need to do is just to add:

您需要做的只是添加:

width: '65%',