Getting the co-ordinates of a component

懵懂的女人 提交于 2019-12-11 03:17:16

问题


How to get the co-ordinates of a JSF component after onclick event ? I need to place an overlay just below an icon that was clicked.

Is there any such in-built facility provided by JSF rather than manually writing a javascript function for that ?


回答1:


In addition to BalusC's answer, here is an example, where a click on a component with id=placeholder (maybe a link or button) will open another component (id=menu) directly below the triggering component. If the mouse is moved away from the triggering component, the menu will disappear:

<script type="text/javascript">
jQuery(document).ready(function() {
  jQuery("#placeholder").click(function(event) {
    //get the position of the placeholder element
    var pos = jQuery(this).offset();
    var height = jQuery(this).height();
    //show the menu directly below the placeholder
    jQuery("#menu").css( { "left": pos.left + "px", "top": (pos.top + height) + "px" } );
    jQuery("#menu").show();
  });
  // hide the menu on mouseout
  jQuery("#placeholder").mouseout(function(event) {
    jQuery("#menu").hide();
  });
});
</script>

The component with id=menu can be a div or a jsf h:panelGroup or any other component. The style attribute with display: none will initially hide the component:

<h:panelGroup style="position: absolute; display: none;" id="menu">
  <!-- content here -->                
</h:panelGroup>

Make sure that the jQuery id selector gets the correct id of the component. E.g. if your elements are inside a form with id=form1, the jQuery call has to look something like this:

  jQuery("#form1\\:placeholder").click(function(event) 

Notice the double backslash.




回答2:


No, there isn't. The position is browser (client) dependent. In the client side there is also totally no means of JSF, it's all just plain HTML/CSS/JS. The location can only be extracted from the HTML DOM element. You'd have to pass it from JS to JSF or do the business job fully in JS instead of JSF.

As PrimeFaces ships with jQuery, your best way to retrieve the element position relative to the document is using jQuery.offset().

var $element = jQuery('#someid');
var offset = $element.offset();
var x = offset.left;
var y = offset.top;
// ...



回答3:


I'd recommend using a JSF component library like RichFaces or IceFaces. Many of them have AJAX capabilities and JavaScript library integration, and therefore have components for doing that kind of thing.



来源:https://stackoverflow.com/questions/6561621/getting-the-co-ordinates-of-a-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!